Skip to content

Commit

Permalink
run black
Browse files Browse the repository at this point in the history
  • Loading branch information
jensens authored and gforcada committed Apr 12, 2023
1 parent 3629714 commit c223935
Show file tree
Hide file tree
Showing 10 changed files with 157 additions and 146 deletions.
2 changes: 1 addition & 1 deletion plone/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__import__('pkg_resources').declare_namespace(__name__)
__import__("pkg_resources").declare_namespace(__name__)
2 changes: 1 addition & 1 deletion plone/behavior/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
import logging


logger = logging.getLogger('plone.behavior')
logger = logging.getLogger("plone.behavior")
23 changes: 11 additions & 12 deletions plone/behavior/annotation.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,34 +19,33 @@ class AnnotationsFactoryImpl:
"""

def __init__(self, context, schema):
self.__dict__['schema'] = schema
self.__dict__['prefix'] = schema.__identifier__ + '.'
self.__dict__['annotations'] = IAnnotations(context)
self.__dict__["schema"] = schema
self.__dict__["prefix"] = schema.__identifier__ + "."
self.__dict__["annotations"] = IAnnotations(context)
alsoProvides(self, schema)

def __getattr__(self, name):
if name not in self.__dict__['schema']:
if name not in self.__dict__["schema"]:
raise AttributeError(name)

annotations = self.__dict__['annotations']
key_name = self.__dict__['prefix'] + name
annotations = self.__dict__["annotations"]
key_name = self.__dict__["prefix"] + name
if key_name not in annotations:
return self.__dict__['schema'][name].missing_value
return self.__dict__["schema"][name].missing_value

return annotations[key_name]

def __setattr__(self, name, value):
if name not in self.__dict__['schema']:
if name not in self.__dict__["schema"]:
super().__setattr__(name, value)
else:
prefixed_name = self.__dict__['prefix'] + name
self.__dict__['annotations'][prefixed_name] = value
prefixed_name = self.__dict__["prefix"] + name
self.__dict__["annotations"][prefixed_name] = value


@provider(ISchemaAwareFactory)
class AnnotationStorage:
"""Behavior adapter factory class for storing data in annotations.
"""
"""Behavior adapter factory class for storing data in annotations."""

def __init__(self, schema):
self.schema = schema
Expand Down
1 change: 0 additions & 1 deletion plone/behavior/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

@implementer(IBehaviorAdapterFactory)
class BehaviorAdapterFactory:

def __init__(self, behavior):
self.behavior = behavior

Expand Down
31 changes: 15 additions & 16 deletions plone/behavior/interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ def supports(behavior_interface):
"""

def enumerateBehaviors():
"""Return an iterable of all the IBehaviors supported by the context.
"""
"""Return an iterable of all the IBehaviors supported by the context."""


class IBehavior(Interface):
Expand All @@ -28,41 +27,41 @@ class IBehavior(Interface):
"""

title = schema.TextLine(
title='Short title of the behavior',
title="Short title of the behavior",
required=True,
)

description = schema.Text(
title='Longer description of the behavior',
title="Longer description of the behavior",
required=False,
)

name = schema.TextLine(
title='Readable short name to be used for behavior lookup',
description='E.g. plone.somebehavior. If not given the full dotted '
'name of the interfaces is used for lookup instead.'
'Recommended, but due to BBB not required.',
title="Readable short name to be used for behavior lookup",
description="E.g. plone.somebehavior. If not given the full dotted "
"name of the interfaces is used for lookup instead."
"Recommended, but due to BBB not required.",
required=False,
)

interface = schema.Object(
title='Interface describing this behavior',
title="Interface describing this behavior",
required=True,
schema=IInterface,
)

marker = schema.Object(
title='Marker interface for objects sporting this behavior',
description='Markers are persisted in the ZODB. '
'Required when a factory is given, because the factory '
'is an adapter adapting the the marker and providing the '
'"interface" of this behavior.',
title="Marker interface for objects sporting this behavior",
description="Markers are persisted in the ZODB. "
"Required when a factory is given, because the factory "
"is an adapter adapting the the marker and providing the "
'"interface" of this behavior.',
required=False,
schema=IInterface,
)

factory = schema.Object(
title='An adapter factory for the behavior',
title="An adapter factory for the behavior",
required=True,
schema=Interface,
)
Expand All @@ -84,7 +83,7 @@ class IBehaviorAdapterFactory(Interface):
"""

behavior = schema.Object(
title='The behavior this is a factory for',
title="The behavior this is a factory for",
schema=IBehavior,
)

Expand Down
91 changes: 49 additions & 42 deletions plone/behavior/metaconfigure.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,81 +22,78 @@ class IBehaviorDirective(Interface):
"""

name = TextLine(
title='Name',
description='Convenience lookup name for this behavior',
title="Name",
description="Convenience lookup name for this behavior",
required=False,
)

title = configuration_fields.MessageID(
title='Title',
description='A user friendly title for this behavior',
title="Title",
description="A user friendly title for this behavior",
required=True,
)

description = configuration_fields.MessageID(
title='Description',
description='A longer description for this behavior',
title="Description",
description="A longer description for this behavior",
required=False,
)

provides = configuration_fields.GlobalInterface(
title='An interface to which the behavior can be adapted',
description='This is what the conditional adapter factory will '
'be registered as providing',
title="An interface to which the behavior can be adapted",
description="This is what the conditional adapter factory will "
"be registered as providing",
required=True,
)

marker = configuration_fields.GlobalInterface(
title='A marker interface to be applied by the behavior',
description='If factory is not given, then this is optional',
title="A marker interface to be applied by the behavior",
description="If factory is not given, then this is optional",
required=False,
)

factory = configuration_fields.GlobalObject(
title='The factory for this behavior',
description='If this is not given, the behavior is assumed to '
'provide a marker interface',
title="The factory for this behavior",
description="If this is not given, the behavior is assumed to "
"provide a marker interface",
required=False,
)

for_ = configuration_fields.GlobalObject(
title='The type of object to register the conditional adapter '
'factory for',
description='This is optional - the default is to register the '
'factory for zope.interface.Interface',
title="The type of object to register the conditional adapter " "factory for",
description="This is optional - the default is to register the "
"factory for zope.interface.Interface",
required=False,
)

name_only = configuration_fields.Bool(
title='Do not register the behavior under the dotted path, but '
'only under the given name',
description='Use this option to register a behavior for the same '
'provides under a different name.',
title="Do not register the behavior under the dotted path, but "
"only under the given name",
description="Use this option to register a behavior for the same "
"provides under a different name.",
required=False,
)

former_dotted_names = TextLine(
title='Space-separated list of dotted names that this behavior was '
'formerly registered under',
description='Use this field in case you change the dotted name, '
'so that the current behavior can be looked up under '
'its former name.',
title="Space-separated list of dotted names that this behavior was "
"formerly registered under",
description="Use this field in case you change the dotted name, "
"so that the current behavior can be looked up under "
"its former name.",
required=False,
)


def _detect_for(factory, marker):
"""if no explicit for is given we need to figure it out.
"""
"""if no explicit for is given we need to figure it out."""
# Attempt to guess the factory's adapted interface and use it as
# the 'for_'.
# at last bastion fallback to '*' (=Interface).
adapts = getattr(factory, '__component_adapts__', [])
adapts = getattr(factory, "__component_adapts__", [])
if len(adapts) == 1:
return adapts[0]
if len(adapts) > 1:
raise ConfigurationError(
'The factory can not be declared as multi-adapter.')
raise ConfigurationError("The factory can not be declared as multi-adapter.")
# down here it means len(adapts) < 1
if marker is not None:
# given we have a marker it is safe to register for the
Expand All @@ -106,10 +103,18 @@ def _detect_for(factory, marker):
return Interface


def behaviorDirective(_context, title, provides, name=None, description=None,
marker=None, factory=None, for_=None, name_only=False,
former_dotted_names=''):

def behaviorDirective(
_context,
title,
provides,
name=None,
description=None,
marker=None,
factory=None,
for_=None,
name_only=False,
former_dotted_names="",
):
if marker is None and factory is None:
# a schema only behavior means usually direct attribute settings on the
# object itself, so the object itself provides the interface.
Expand All @@ -118,12 +123,13 @@ def behaviorDirective(_context, title, provides, name=None, description=None,

if marker is not None and factory is None and marker is not provides:
raise ConfigurationError(
'You cannot specify a different \'marker\' and \'provides\' if '
'there is no adapter factory for the provided interface.')
"You cannot specify a different 'marker' and 'provides' if "
"there is no adapter factory for the provided interface."
)
if name_only and name is None:
raise ConfigurationError(
'If you decide to only register by \'name\', a name must '
'be given.')
"If you decide to only register by 'name', a name must " "be given."
)

# Instantiate the real factory if it's the schema-aware type. We do
# this here so that the for_ interface may take this into account.
Expand Down Expand Up @@ -167,8 +173,9 @@ def behaviorDirective(_context, title, provides, name=None, description=None,
if factory is None:
if for_ is not None:
logger.warn(
'Specifying \'for\' in behavior \'{}\' if no \'factory\' is '
'given has no effect and is superfluous.'.format(title))
"Specifying 'for' in behavior '{}' if no 'factory' is "
"given has no effect and is superfluous.".format(title)
)
# w/o factory we're done here: schema only behavior
return

Expand Down
58 changes: 33 additions & 25 deletions plone/behavior/registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,16 @@

@implementer(IBehavior)
class BehaviorRegistration:

def __init__(self, title, description, interface,
marker, factory, name=None, former_dotted_names=''):
def __init__(
self,
title,
description,
interface,
marker,
factory,
name=None,
former_dotted_names="",
):
self.title = title
self.description = description
self.interface = interface
Expand All @@ -42,36 +49,34 @@ def __repr__(self):
if self.marker is not None:
marker_info = self.marker.__identifier__
elif self.marker is not None and self.marker is not self.interface:
marker_info = '(uses schema as marker)'
marker_info = "(uses schema as marker)"
else:
marker_info = '(no marker is set)'
marker_info = "(no marker is set)"
info = {
'class': self.__class__.__name__,
'id': id(self),
'name': self.name or '(unique name not set)',
'identifier': self.interface.__identifier__,
'marker': marker_info,
'factory': text_type(self.factory),
'title': self.title or '(no title)',
'description': textwrap.fill(
self.description or '(no description)',
subsequent_indent=' ',
"class": self.__class__.__name__,
"id": id(self),
"name": self.name or "(unique name not set)",
"identifier": self.interface.__identifier__,
"marker": marker_info,
"factory": text_type(self.factory),
"title": self.title or "(no title)",
"description": textwrap.fill(
self.description or "(no description)",
subsequent_indent=" ",
),
'extra_info': (
self.former_dotted_names and
f'\n former dotted names: {self.former_dotted_names}'
"extra_info": (
self.former_dotted_names
and f"\n former dotted names: {self.former_dotted_names}"
),
}
return REGISTRATION_REPR.format(**info)


class BehaviorRegistrationNotFound(Exception):
"""Exception thrown if behavior registration lookup fails.
"""
"""Exception thrown if behavior registration lookup fails."""


def lookup_behavior_registration(
name=None, identifier=None, warn_about_fallback=True):
def lookup_behavior_registration(name=None, identifier=None, warn_about_fallback=True):
"""Look up behavior registration either by name or interface identifier.
Fall back to checking the former_dotted_names if the lookup is not
successful.
Expand All @@ -80,9 +85,9 @@ def lookup_behavior_registration(
``BehaviorRegistrationNotFound`` is thrown if lookup fails.
"""
try:
assert(name or identifier)
assert name or identifier
except AssertionError:
raise ValueError('Either ``name`` or ``identifier`` must be given')
raise ValueError("Either ``name`` or ``identifier`` must be given")
# identifier rules if given
if identifier:
name = identifier
Expand All @@ -97,6 +102,9 @@ def lookup_behavior_registration(
logger.warn(
'The dotted name "{}" is deprecated. It has been '
'changed to "{}"'.format(
name, behavior.interface.__identifier__, ))
name,
behavior.interface.__identifier__,
)
)
return behavior
raise BehaviorRegistrationNotFound(name)
Loading

0 comments on commit c223935

Please sign in to comment.