Projects
openEuler:Mainline
python-zope-interface
Sign Up
Log In
Username
Password
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
Expand all
Collapse all
Changes of Revision 7
View file
_service:tar_scm:python-zope-interface.spec
Changed
@@ -1,11 +1,11 @@ %global _empty_manifest_terminate_build 0 Name: python-zope-interface -Version: 5.5.2 +Version: 6.0 Release: 1 Summary: Interfaces for Python License: ZPL 2.1 URL: https://github.com/zopefoundation/zope.interface -Source0: https://files.pythonhosted.org/packages/38/6f/fbfb7dde38be7e5644bb342c4c7cdc444cd5e2ffbd70d091263b3858a8cb/zope.interface-5.5.2.tar.gz +Source0: https://files.pythonhosted.org/packages/7a/62/f0d012151af1e8cc0a6c97db74b78141143425dcdf81bc7960c498e28960/zope.interface-6.0.tar.gz %description This package is intended to be independently reusable in any Python project. It is maintained by the Zope Toolkit project. @@ -88,6 +88,9 @@ %{_docdir}/* %changelog +* Mon Jul 10 2023 chenzixuan <chenzixuan@kylinos.cn> - 6.0-1 +- Upgrade package to version 6.0 + * Thu Dec 15 2022 chendexi <chendexi@kylinos.cn> - 5.5.2-1 - Upgrade package to version 5.5.2
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build
Deleted
-(directory)
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/doctest
Deleted
-(directory)
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/doctest/output.txt
Deleted
@@ -1,65 +0,0 @@ -Results of doctest builder run on 2022-11-03 13:55:30 -===================================================== - -Document: api/specifications ----------------------------- -1 items passed all tests: - 109 tests in default -109 tests in 1 items. -109 passed and 0 failed. -Test passed. - -Document: verify ----------------- -1 items passed all tests: - 78 tests in default -78 tests in 1 items. -78 passed and 0 failed. -Test passed. - -Document: human ---------------- -1 items passed all tests: - 18 tests in default -18 tests in 1 items. -18 passed and 0 failed. -Test passed. - -Document: api/declarations --------------------------- -1 items passed all tests: - 302 tests in default -302 tests in 1 items. -302 passed and 0 failed. -Test passed. - -Document: adapter ------------------ -1 items passed all tests: - 164 tests in default -164 tests in 1 items. -164 passed and 0 failed. -Test passed. - -Document: README ----------------- -1 items passed all tests: - 218 tests in default -218 tests in 1 items. -218 passed and 0 failed. -Test passed. - -Document: foodforthought ------------------------- -1 items passed all tests: - 25 tests in default -25 tests in 1 items. -25 passed and 0 failed. -Test passed. - -Doctest summary -=============== - 914 tests - 0 failures in tests - 0 failures in setup code - 0 failures in cleanup code
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html
Deleted
-(directory)
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources
Deleted
-(directory)
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/README.rst.txt
Deleted
@@ -1,1357 +0,0 @@ -============ - Interfaces -============ - -.. currentmodule:: zope.interface - -Interfaces are objects that specify (document) the external behavior -of objects that "provide" them. An interface specifies behavior -through: - -- Informal documentation in a doc string - -- Attribute definitions - -- Invariants, which are conditions that must hold for objects that - provide the interface - -Attribute definitions specify specific attributes. They define the -attribute name and provide documentation and constraints of attribute -values. Attribute definitions can take a number of forms, as we'll -see below. - -Defining interfaces -=================== - -Interfaces are defined using Python ``class`` statements: - -.. doctest:: - - >>> import zope.interface - >>> class IFoo(zope.interface.Interface): - ... """Foo blah blah""" - ... - ... x = zope.interface.Attribute("""X blah blah""") - ... - ... def bar(q, r=None): - ... """bar blah blah""" - -In the example above, we've created an interface, :class:`IFoo`. We -subclassed :class:`zope.interface.Interface`, which is an ancestor interface for -all interfaces, much as ``object`` is an ancestor of all new-style -classes #create_. The interface is not a class, it's an Interface, -an instance of :class:`zope.interface.interface.InterfaceClass`: - -.. doctest:: - - >>> type(IFoo) - <class 'zope.interface.interface.InterfaceClass'> - -We can ask for the interface's documentation: - -.. doctest:: - - >>> IFoo.__doc__ - 'Foo blah blah' - -and its name: - -.. doctest:: - - >>> IFoo.__name__ - 'IFoo' - -and even its module: - -.. doctest:: - - >>> IFoo.__module__ - 'builtins' - -The interface defined two attributes: - -``x`` - This is the simplest form of attribute definition. It has a name - and a doc string. It doesn't formally specify anything else. - -``bar`` - This is a method. A method is defined via a function definition. A - method is simply an attribute constrained to be a callable with a - particular signature, as provided by the function definition. - - Note that ``bar`` doesn't take a ``self`` argument. Interfaces document - how an object is *used*. When calling instance methods, you don't - pass a ``self`` argument, so a ``self`` argument isn't included in the - interface signature. The ``self`` argument in instance methods is - really an implementation detail of Python instances. Other objects, - besides instances can provide interfaces and their methods might not - be instance methods. For example, modules can provide interfaces and - their methods are usually just functions. Even instances can have - methods that are not instance methods. - -You can access the attributes defined by an interface using mapping -syntax: - -.. doctest:: - - >>> x = IFoo'x' - >>> type(x) - <class 'zope.interface.interface.Attribute'> - >>> x.__name__ - 'x' - >>> x.__doc__ - 'X blah blah' - - >>> IFoo.get('x').__name__ - 'x' - - >>> IFoo.get('y') - -You can use ``in`` to determine if an interface defines a name: - -.. doctest:: - - >>> 'x' in IFoo - True - -You can iterate over interfaces to get the names they define: - -.. doctest:: - - >>> names = list(IFoo) - >>> names.sort() - >>> names - 'bar', 'x' - -Remember that interfaces aren't classes. You can't access attribute -definitions as attributes of interfaces: - -.. doctest:: - - >>> IFoo.x - Traceback (most recent call last): - File "<stdin>", line 1, in ? - AttributeError: 'InterfaceClass' object has no attribute 'x' - -Methods provide access to the method signature: - -.. doctest:: - - >>> bar = IFoo'bar' - >>> bar.getSignatureString() - '(q, r=None)' - -TODO - Methods really should have a better API. This is something that - needs to be improved. - -Declaring interfaces -==================== - -Having defined interfaces, we can *declare* that objects provide -them. Before we describe the details, lets define some terms: - -*provide* - We say that objects *provide* interfaces. If an object provides an - interface, then the interface specifies the behavior of the - object. In other words, interfaces specify the behavior of the - objects that provide them. - -*implement* - We normally say that classes *implement* interfaces. If a class - implements an interface, then the instances of the class provide - the interface. Objects provide interfaces that their classes - implement #factory_. (Objects can provide interfaces directly, - in addition to what their classes implement.) - - It is important to note that classes don't usually provide the - interfaces that they implement. - - We can generalize this to factories. For any callable object we - can declare that it produces objects that provide some interfaces - by saying that the factory implements the interfaces. - -Now that we've defined these terms, we can talk about the API for -declaring interfaces. - -Declaring implemented interfaces --------------------------------- - -The most common way to declare interfaces is using the `implementer` -decorator on a class: - -.. doctest:: - - >>> @zope.interface.implementer(IFoo) - ... class Foo: - ... - ... def __init__(self, x=None): - ... self.x = x - ... - ... def bar(self, q, r=None): - ... return q, r, self.x - ... - ... def __repr__(self): - ... return "Foo(%s)" % self.x - - -In this example, we declared that ``Foo`` implements ``IFoo``. This means -that instances of ``Foo`` provide ``IFoo``. Having made this declaration, -there are several ways we can introspect the declarations. First, we -can ask an interface whether it is implemented by a class: - -.. doctest:: - - >>> IFoo.implementedBy(Foo) - True - -And we can ask whether an interface is provided by an object: - -.. doctest:: - - >>> foo = Foo() - >>> IFoo.providedBy(foo) - True - -Of course, ``Foo`` doesn't *provide* ``IFoo``, it *implements* it: - -.. doctest:: - - >>> IFoo.providedBy(Foo) - False - -We can also ask what interfaces are implemented by a class: - -.. doctest:: - - >>> list(zope.interface.implementedBy(Foo)) - <InterfaceClass builtins.IFoo> - -It's an error to ask for interfaces implemented by a non-callable -object: - -.. doctest:: - - >>> IFoo.implementedBy(foo) - Traceback (most recent call last): - ... - TypeError: ('ImplementedBy called for non-factory', Foo(None)) - - >>> list(zope.interface.implementedBy(foo)) - Traceback (most recent call last): - ... - TypeError: ('ImplementedBy called for non-factory', Foo(None)) - -Similarly, we can ask what interfaces are provided by an object: - -.. doctest:: - - >>> list(zope.interface.providedBy(foo)) - <InterfaceClass builtins.IFoo> - >>> list(zope.interface.providedBy(Foo)) - - -We can declare interfaces implemented by other factories (besides -classes). We do this using the same `implementer` decorator. - -.. doctest:: - - >>> @zope.interface.implementer(IFoo) - ... def yfoo(y): - ... foo = Foo() - ... foo.y = y - ... return foo - - >>> list(zope.interface.implementedBy(yfoo)) - <InterfaceClass builtins.IFoo> - -Note that the implementer decorator may modify its argument. Callers -should not assume that a new object is created. - -Using implementer also works on callable objects. This is used by -:py:mod:`zope.formlib`, as an example: - -.. doctest:: - - >>> class yfactory: - ... def __call__(self, y): - ... foo = Foo() - ... foo.y = y - ... return foo - >>> yfoo = yfactory() - >>> yfoo = zope.interface.implementer(IFoo)(yfoo) - - >>> list(zope.interface.implementedBy(yfoo)) - <InterfaceClass builtins.IFoo> - -XXX: Double check and update these version numbers: - -In :py:mod:`zope.interface` 3.5.2 and lower, the implementer decorator can not -be used for classes, but in 3.6.0 and higher it can: - -.. doctest:: - - >>> Foo = zope.interface.implementer(IFoo)(Foo) - >>> list(zope.interface.providedBy(Foo())) - <InterfaceClass builtins.IFoo> - -Note that class decorators using the ``@implementer(IFoo)`` syntax are only -supported in Python 2.6 and later. - -.. autofunction:: implementer - :noindex: - - .. XXX: Duplicate description. - -Declaring provided interfaces ------------------------------ - -We can declare interfaces directly provided by objects. Suppose that -we want to document what the ``__init__`` method of the ``Foo`` class -does. It's not *really* part of ``IFoo``. You wouldn't normally call -the ``__init__`` method on Foo instances. Rather, the ``__init__`` method -is part of ``Foo``'s ``__call__`` method: - -.. doctest:: - - >>> class IFooFactory(zope.interface.Interface): - ... """Create foos""" - ... - ... def __call__(x=None): - ... """Create a foo - ... - ... The argument provides the initial value for x ... - ... """ - -It's the class that provides this interface, so we declare the -interface on the class: - -.. doctest:: - - >>> zope.interface.directlyProvides(Foo, IFooFactory) - -And then, we'll see that Foo provides some interfaces: - -.. doctest:: - - >>> list(zope.interface.providedBy(Foo)) - <InterfaceClass builtins.IFooFactory> - >>> IFooFactory.providedBy(Foo) - True - -Declaring class interfaces is common enough that there's a special -decorator for it, `provider`: - -.. doctest:: - - >>> @zope.interface.implementer(IFoo) - ... @zope.interface.provider(IFooFactory) - ... class Foo2: - ... - ... def __init__(self, x=None): - ... self.x = x - ... - ... def bar(self, q, r=None): - ... return q, r, self.x - ... - ... def __repr__(self): - ... return "Foo(%s)" % self.x - - >>> list(zope.interface.providedBy(Foo2)) - <InterfaceClass builtins.IFooFactory> - >>> IFooFactory.providedBy(Foo2) - True - -There's a similar function, ``moduleProvides``, that supports interface -declarations from within module definitions. For example, see the use -of ``moduleProvides`` call in ``zope.interface.__init__``, which declares that -the package ``zope.interface`` provides ``IInterfaceDeclaration``. - -Sometimes, we want to declare interfaces on instances, even though -those instances get interfaces from their classes. Suppose we create -a new interface, ``ISpecial``: - -.. doctest:: - - >>> class ISpecial(zope.interface.Interface): - ... reason = zope.interface.Attribute("Reason why we're special") - ... def brag(): - ... "Brag about being special" - -We can make an existing foo instance special by providing ``reason`` -and ``brag`` attributes: - -.. doctest:: - - >>> foo.reason = 'I just am' - >>> def brag(): - ... return "I'm special!" - >>> foo.brag = brag - >>> foo.reason - 'I just am' - >>> foo.brag() - "I'm special!" - -and by declaring the interface: - -.. doctest:: - - >>> zope.interface.directlyProvides(foo, ISpecial) - -then the new interface is included in the provided interfaces: - -.. doctest:: - - >>> ISpecial.providedBy(foo) - True - >>> list(zope.interface.providedBy(foo)) - <InterfaceClass builtins.ISpecial>, <InterfaceClass builtins.IFoo> - -We can find out what interfaces are directly provided by an object: - -.. doctest:: - - >>> list(zope.interface.directlyProvidedBy(foo)) - <InterfaceClass builtins.ISpecial> - - >>> newfoo = Foo() - >>> list(zope.interface.directlyProvidedBy(newfoo)) - - -.. autofunction:: provider - :noindex: - - .. XXX: Duplicate description. - -Inherited declarations ----------------------- - -Normally, declarations are inherited: - -.. doctest:: - - >>> @zope.interface.implementer(ISpecial) - ... class SpecialFoo(Foo): - ... reason = 'I just am' - ... def brag(self): - ... return "I'm special because %s" % self.reason - - >>> list(zope.interface.implementedBy(SpecialFoo)) - <InterfaceClass builtins.ISpecial>, <InterfaceClass builtins.IFoo> - - >>> list(zope.interface.providedBy(SpecialFoo())) - <InterfaceClass builtins.ISpecial>, <InterfaceClass builtins.IFoo> - -Sometimes, you don't want to inherit declarations. In that case, you -can use ``implementer_only``, instead of ``implementer``: - -.. doctest:: - - >>> @zope.interface.implementer_only(ISpecial) - ... class Special(Foo): - ... reason = 'I just am' - ... def brag(self): - ... return "I'm special because %s" % self.reason - - >>> list(zope.interface.implementedBy(Special)) - <InterfaceClass builtins.ISpecial> - - >>> list(zope.interface.providedBy(Special())) - <InterfaceClass builtins.ISpecial> - -External declarations ---------------------- - -Normally, we make implementation declarations as part of a class -definition. Sometimes, we may want to make declarations from outside -the class definition. For example, we might want to declare interfaces -for classes that we didn't write. The function ``classImplements`` can -be used for this purpose: - -.. doctest:: - - >>> class C: - ... pass - - >>> zope.interface.classImplements(C, IFoo) - >>> list(zope.interface.implementedBy(C)) - <InterfaceClass builtins.IFoo> - -.. autofunction:: classImplements - :noindex: - -We can use ``classImplementsOnly`` to exclude inherited interfaces: - -.. doctest:: - - >>> class C(Foo): - ... pass - - >>> zope.interface.classImplementsOnly(C, ISpecial) - >>> list(zope.interface.implementedBy(C)) - <InterfaceClass builtins.ISpecial> - -.. autofunction:: classImplementsOnly - :noindex: - - .. XXX: Duplicate description. - -Declaration Objects -------------------- - -When we declare interfaces, we create *declaration* objects. When we -query declarations, declaration objects are returned: - -.. doctest:: - - >>> type(zope.interface.implementedBy(Special)) - <class 'zope.interface.declarations.Implements'> - -Declaration objects and interface objects are similar in many ways. In -fact, they share a common base class. The important thing to realize -about them is that they can be used where interfaces are expected in -declarations. Here's a silly example: - -.. doctest:: - - >>> @zope.interface.implementer_only( - ... zope.interface.implementedBy(Foo), - ... ISpecial, - ... ) - ... class Special2(object): - ... reason = 'I just am' - ... def brag(self): - ... return "I'm special because %s" % self.reason - -The declaration here is almost the same as -``zope.interface.implementer(ISpecial)``, except that the order of -interfaces in the resulting declaration is different: - -.. doctest:: - - >>> list(zope.interface.implementedBy(Special2)) - <InterfaceClass builtins.IFoo>, <InterfaceClass builtins.ISpecial> - - -Interface Inheritance -===================== - -Interfaces can extend other interfaces. They do this simply by listing -the other interfaces as base interfaces: - -.. doctest:: - - >>> class IBlat(zope.interface.Interface): - ... """Blat blah blah""" - ... - ... y = zope.interface.Attribute("y blah blah") - ... def eek(): - ... """eek blah blah""" - - >>> IBlat.__bases__ - (<InterfaceClass zope.interface.Interface>,) - - >>> class IBaz(IFoo, IBlat): - ... """Baz blah""" - ... def eek(a=1): - ... """eek in baz blah""" - ... - - >>> IBaz.__bases__ - (<InterfaceClass builtins.IFoo>, <InterfaceClass builtins.IBlat>) - - >>> names = list(IBaz) - >>> names.sort() - >>> names - 'bar', 'eek', 'x', 'y' - -Note that ``IBaz`` overrides ``eek``: - -.. doctest:: - - >>> IBlat'eek'.__doc__ - 'eek blah blah' - >>> IBaz'eek'.__doc__ - 'eek in baz blah' - -We were careful to override ``eek`` in a compatible way. When extending -an interface, the extending interface should be compatible #compat_ -with the extended interfaces. - -We can ask whether one interface extends another: - -.. doctest:: - - >>> IBaz.extends(IFoo) - True - >>> IBlat.extends(IFoo) - False - -Note that interfaces don't extend themselves: - -.. doctest:: - - >>> IBaz.extends(IBaz) - False - -Sometimes we wish they did, but we can instead use ``isOrExtends``: - -.. doctest:: - - >>> IBaz.isOrExtends(IBaz) - True - >>> IBaz.isOrExtends(IFoo) - True - >>> IFoo.isOrExtends(IBaz) - False - -When we iterate over an interface, we get all of the names it defines, -including names defined by base interfaces. Sometimes, we want *just* -the names defined by the interface directly. We can use the ``names`` -method for that: - -.. doctest:: - - >>> list(IBaz.names()) - 'eek' - -Inheritance of attribute specifications ---------------------------------------- - -An interface may override attribute definitions from base interfaces. -If two base interfaces define the same attribute, the attribute is -inherited from the most specific interface. For example, with: - -.. doctest:: - - >>> class IBase(zope.interface.Interface): - ... - ... def foo(): - ... "base foo doc" - - >>> class IBase1(IBase): - ... pass - - >>> class IBase2(IBase): - ... - ... def foo(): - ... "base2 foo doc" - - >>> class ISub(IBase1, IBase2): - ... pass - -``ISub``'s definition of ``foo`` is the one from ``IBase2``, since ``IBase2`` is more -specific than ``IBase``: - -.. doctest:: - - >>> ISub'foo'.__doc__ - 'base2 foo doc' - -Note that this differs from a depth-first search. - -Sometimes, it's useful to ask whether an interface defines an -attribute directly. You can use the direct method to get a directly -defined definitions: - -.. doctest:: - - >>> IBase.direct('foo').__doc__ - 'base foo doc' - - >>> ISub.direct('foo') - -Specifications --------------- - -Interfaces and declarations are both special cases of specifications. -What we described above for interface inheritance applies to both -declarations and specifications. Declarations actually extend the -interfaces that they declare: - -.. doctest:: - - >>> @zope.interface.implementer(IBaz) - ... class Baz(object): - ... pass - - >>> baz_implements = zope.interface.implementedBy(Baz) - >>> baz_implements.__bases__ - (<InterfaceClass builtins.IBaz>, classImplements(object)) - - >>> baz_implements.extends(IFoo) - True - - >>> baz_implements.isOrExtends(IFoo) - True - >>> baz_implements.isOrExtends(baz_implements) - True - -Specifications (interfaces and declarations) provide an ``__sro__`` -that lists the specification and all of it's ancestors: - -.. doctest:: - - >>> from pprint import pprint - >>> pprint(baz_implements.__sro__) - (classImplements(Baz, IBaz), - <InterfaceClass builtins.IBaz>, - <InterfaceClass builtins.IFoo>, - <InterfaceClass builtins.IBlat>, - classImplements(object), - <InterfaceClass zope.interface.Interface>) - >>> class IBiz(zope.interface.Interface): - ... pass - >>> @zope.interface.implementer(IBiz) - ... class Biz(Baz): - ... pass - >>> pprint(zope.interface.implementedBy(Biz).__sro__) - (classImplements(Biz, IBiz), - <InterfaceClass builtins.IBiz>, - classImplements(Baz, IBaz), - <InterfaceClass builtins.IBaz>, - <InterfaceClass builtins.IFoo>, - <InterfaceClass builtins.IBlat>, - classImplements(object), - <InterfaceClass zope.interface.Interface>) - -Tagged Values -============= - -.. autofunction:: taggedValue - -Interfaces and attribute descriptions support an extension mechanism, -borrowed from UML, called "tagged values" that lets us store extra -data: - -.. doctest:: - - >>> IFoo.setTaggedValue('date-modified', '2004-04-01') - >>> IFoo.setTaggedValue('author', 'Jim Fulton') - >>> IFoo.getTaggedValue('date-modified') - '2004-04-01' - >>> IFoo.queryTaggedValue('date-modified') - '2004-04-01' - >>> IFoo.queryTaggedValue('datemodified') - >>> tags = list(IFoo.getTaggedValueTags()) - >>> tags.sort() - >>> tags - 'author', 'date-modified' - -Function attributes are converted to tagged values when method -attribute definitions are created: - -.. doctest:: - - >>> class IBazFactory(zope.interface.Interface): - ... def __call__(): - ... "create one" - ... __call__.return_type = IBaz - - >>> IBazFactory'__call__'.getTaggedValue('return_type') - <InterfaceClass builtins.IBaz> - -Tagged values can also be defined from within an interface definition: - -.. doctest:: - - >>> class IWithTaggedValues(zope.interface.Interface): - ... zope.interface.taggedValue('squish', 'squash') - >>> IWithTaggedValues.getTaggedValue('squish') - 'squash' - -Tagged values are inherited in the same way that attribute and method -descriptions are. Inheritance can be ignored by using the "direct" -versions of functions. - -.. doctest:: - - >>> class IExtendsIWithTaggedValues(IWithTaggedValues): - ... zope.interface.taggedValue('child', True) - >>> IExtendsIWithTaggedValues.getTaggedValue('child') - True - >>> IExtendsIWithTaggedValues.getDirectTaggedValue('child') - True - >>> IExtendsIWithTaggedValues.getTaggedValue('squish') - 'squash' - >>> print(IExtendsIWithTaggedValues.queryDirectTaggedValue('squish')) - None - >>> IExtendsIWithTaggedValues.setTaggedValue('squish', 'SQUASH') - >>> IExtendsIWithTaggedValues.getTaggedValue('squish') - 'SQUASH' - >>> IExtendsIWithTaggedValues.getDirectTaggedValue('squish') - 'SQUASH' - - -Invariants -========== - -.. autofunction:: invariant - -Interfaces can express conditions that must hold for objects that -provide them. These conditions are expressed using one or more -invariants. Invariants are callable objects that will be called with -an object that provides an interface. An invariant raises an ``Invalid`` -exception if the condition doesn't hold. Here's an example: - -.. doctest:: - - >>> class RangeError(zope.interface.Invalid): - ... """A range has invalid limits""" - ... def __repr__(self): - ... return "RangeError(%r)" % self.args - - >>> def range_invariant(ob): - ... if ob.max < ob.min: - ... raise RangeError(ob) - -Given this invariant, we can use it in an interface definition: - -.. doctest:: - - >>> class IRange(zope.interface.Interface): - ... min = zope.interface.Attribute("Lower bound") - ... max = zope.interface.Attribute("Upper bound") - ... - ... zope.interface.invariant(range_invariant) - -Interfaces have a method for checking their invariants: - -.. doctest:: - - >>> @zope.interface.implementer(IRange) - ... class Range(object): - ... def __init__(self, min, max): - ... self.min, self.max = min, max - ... - ... def __repr__(self): - ... return "Range(%s, %s)" % (self.min, self.max) - - >>> IRange.validateInvariants(Range(1,2)) - >>> IRange.validateInvariants(Range(1,1)) - >>> IRange.validateInvariants(Range(2,1)) - Traceback (most recent call last): - ... - RangeError: Range(2, 1) - -If you have multiple invariants, you may not want to stop checking -after the first error. If you pass a list to ``validateInvariants``, -then a single ``Invalid`` exception will be raised with the list of -exceptions as its argument: - -.. doctest:: - - >>> from zope.interface.exceptions import Invalid - >>> errors = - >>> try: - ... IRange.validateInvariants(Range(2,1), errors) - ... except Invalid as e: - ... str(e) - 'RangeError(Range(2, 1))' - -And the list will be filled with the individual exceptions: - -.. doctest:: - - >>> errors - RangeError(Range(2, 1)) - - >>> del errors: - -Adaptation -========== - -Interfaces can be called to perform *adaptation*. Adaptation is the -process of converting an object to an object implementing the -interface. For example, in mathematics, to represent a point in space -or on a graph there's the familiar Cartesian coordinate system using -``CartesianPoint(x, y)``, and there's also the Polar coordinate system -using ``PolarPoint(r, theta)``, plus several others (homogeneous, -log-polar, etc). Polar points are most convenient for some types of -operations, but cartesian points may make more intuitive sense to most -people. Before printing an arbitrary point, we might want to *adapt* it -to ``ICartesianPoint``, or before performing some mathematical -operation you might want to adapt the arbitrary point to ``IPolarPoint``. - -The semantics are based on those of the :pep:`246` ``adapt`` -function. - -If an object cannot be adapted, then a ``TypeError`` is raised: - -.. doctest:: - - >>> class ICartesianPoint(zope.interface.Interface): - ... x = zope.interface.Attribute("Distance from origin along x axis") - ... y = zope.interface.Attribute("Distance from origin along y axis") - - >>> ICartesianPoint(0) - Traceback (most recent call last): - ... - TypeError: ('Could not adapt', 0, <InterfaceClass builtins.ICartesianPoint>) - - -unless a default value is provided as a second positional argument; -this value is not checked to see if it implements the interface: - -.. doctest:: - - >>> ICartesianPoint(0, 'bob') - 'bob' - -If an object already implements the interface, then it will be returned: - -.. doctest:: - - >>> @zope.interface.implementer(ICartesianPoint) - ... class CartesianPoint(object): - ... """The default cartesian point is the origin.""" - ... def __init__(self, x=0, y=0): - ... self.x = x - ... self.y = y - ... def __repr__(self): - ... return "CartesianPoint(%s, %s)" % (self.x, self.y) - - >>> obj = CartesianPoint() - >>> ICartesianPoint(obj) is obj - True - -``__conform__`` ---------------- - -:pep:`246` outlines a requirement: - - When the object knows about the interface, and either considers - itself compliant, or knows how to wrap itself suitably. - -This is handled with ``__conform__``. If an object implements -``__conform__``, then it will be used to give the object the chance to -decide if it knows about the interface. This is true even if the class -declares that it implements the interface. - -.. doctest:: - - >>> @zope.interface.implementer(ICartesianPoint) - ... class C(object): - ... def __conform__(self, proto): - ... return "This could be anything." - - >>> ICartesianPoint(C()) - 'This could be anything.' - -If ``__conform__`` returns ``None`` (because the object is unaware of -the interface), then the rest of the adaptation process will continue. -Here, we demonstrate that if the object already provides the -interface, it is returned. - -.. doctest:: - - >>> @zope.interface.implementer(ICartesianPoint) - ... class C(object): - ... def __conform__(self, proto): - ... return None - - >>> c = C() - >>> ICartesianPoint(c) is c - True - - -Adapter hooks (see :ref:`adapt_adapter_hooks`) will also be used, if present (after -a ``__conform__`` method, if any, has been tried): - -.. doctest:: - - >>> from zope.interface.interface import adapter_hooks - >>> def adapt_tuple_to_point(iface, obj): - ... if isinstance(obj, tuple) and len(obj) == 2: - ... return CartesianPoint(*obj) - - >>> adapter_hooks.append(adapt_tuple_to_point) - >>> ICartesianPoint((1, 1)) - CartesianPoint(1, 1) - - >>> adapter_hooks.remove(adapt_tuple_to_point) - >>> ICartesianPoint((1, 1)) - Traceback (most recent call last): - ... - TypeError: ('Could not adapt', (1, 1), <InterfaceClass builtins.ICartesianPoint>) - -.. _adapt_adapter_hooks: - -``__adapt__`` and adapter hooks -------------------------------- - -Interfaces implement the :pep:`246` ``__adapt__`` method to satisfy -the requirement: - - When the interface knows about the object, and either the object - already complies or the interface knows how to suitably wrap the - object. - -This method is normally not called directly. It is called by the -:pep:`246` adapt framework and by the interface ``__call__`` operator -once ``__conform__`` (if any) has failed. - -The ``__adapt__`` method is responsible for adapting an object to the -receiver. - -The default version returns ``None`` (because by default no interface -"knows how to suitably wrap the object"): - -.. doctest:: - - >>> ICartesianPoint.__adapt__(0) - -unless the object given provides the interface ("the object already complies"): - -.. doctest:: - - >>> @zope.interface.implementer(ICartesianPoint) - ... class C(object): - ... pass - - >>> obj = C() - >>> ICartesianPoint.__adapt__(obj) is obj - True - -.. rubric:: Customizing ``__adapt__`` in an interface - -It is possible to replace or customize the ``__adapt___`` -functionality for particular interfaces, if that interface "knows how -to suitably wrap an object". This method should return the adapted -object if it knows how, or call the super class to continue with the -default adaptation process. - -.. doctest:: - - >>> import math - >>> class IPolarPoint(zope.interface.Interface): - ... r = zope.interface.Attribute("Distance from center.") - ... theta = zope.interface.Attribute("Angle from horizontal.") - ... @zope.interface.interfacemethod - ... def __adapt__(self, obj): - ... if ICartesianPoint.providedBy(obj): - ... # Convert to polar coordinates. - ... r = math.sqrt(obj.x ** 2 + obj.y ** 2) - ... theta = math.acos(obj.x / r) - ... theta = math.degrees(theta) - ... return PolarPoint(r, theta) - ... return super(type(IPolarPoint), self).__adapt__(obj) - - >>> @zope.interface.implementer(IPolarPoint) - ... class PolarPoint(object): - ... def __init__(self, r=0, theta=0): - ... self.r = r; self.theta = theta - ... def __repr__(self): - ... return "PolarPoint(%s, %s)" % (self.r, self.theta) - >>> IPolarPoint(CartesianPoint(0, 1)) - PolarPoint(1.0, 90.0) - >>> IPolarPoint(PolarPoint()) - PolarPoint(0, 0) - -.. seealso:: :func:`zope.interface.interfacemethod`, which explains - how to override functions in interface definitions and why, prior - to Python 3.6, the zero-argument version of `super` cannot be used. - -.. rubric:: Using adapter hooks for loose coupling - -Commonly, the author of the interface doesn't know how to wrap all -possible objects, and neither does the author of an object know how to -``__conform__`` to all possible interfaces. To support decoupling -interfaces and objects, interfaces support the concept of "adapter -hooks." Adapter hooks are a global sequence of callables -``hook(interface, object)`` that are called, in order, from the -default ``__adapt__`` method until one returns a non-``None`` result. - -.. note:: - In many applications, a :doc:`adapter` is installed as - the first or only adapter hook. - -We'll install a hook that adapts from a 2D ``(x, y)`` Cartesian point -on a plane to a three-dimensional point ``(x, y, z)`` by assuming the -``z`` coordinate is 0. First, we'll define this new interface and an -implementation: - -.. doctest:: - - >>> class ICartesianPoint3D(ICartesianPoint): - ... z = zope.interface.Attribute("Depth.") - >>> @zope.interface.implementer(ICartesianPoint3D) - ... class CartesianPoint3D(CartesianPoint): - ... def __init__(self, x=0, y=0, z=0): - ... CartesianPoint.__init__(self, x, y) - ... self.z = 0 - ... def __repr__(self): - ... return "CartesianPoint3D(%s, %s, %s)" % (self.x, self.y, self.z) - - -We install a hook by simply adding it to the ``adapter_hooks`` list: - -.. doctest:: - - >>> from zope.interface.interface import adapter_hooks - >>> def returns_none(iface, obj): - ... print("(First adapter hook returning None.)") - >>> def adapt_2d_to_3d(iface, obj): - ... if iface == ICartesianPoint3D and ICartesianPoint.providedBy(obj): - ... return CartesianPoint3D(obj.x, obj.y, 0) - >>> adapter_hooks.append(returns_none) - >>> adapter_hooks.append(adapt_2d_to_3d) - >>> ICartesianPoint3D.__adapt__(CartesianPoint()) - (First adapter hook returning None.) - CartesianPoint3D(0, 0, 0) - >>> ICartesianPoint3D(CartesianPoint()) - (First adapter hook returning None.) - CartesianPoint3D(0, 0, 0) - -Hooks can be uninstalled by removing them from the list: - -.. doctest:: - - >>> adapter_hooks.remove(returns_none) - >>> adapter_hooks.remove(adapt_2d_to_3d) - >>> ICartesianPoint3D.__adapt__(CartesianPoint()) - -.. _global_persistence: - -Persistence, Sorting, Equality and Hashing -========================================== - -.. tip:: For the practical implications of what's discussed below, and - some potential problems, see :ref:`spec_eq_hash`. - -Just like Python classes, interfaces are designed to inexpensively -support persistence using Python's standard :mod:`pickle` module. This -means that one process can send a *reference* to an interface to another -process in the form of a byte string, and that other process can load -that byte string and get the object that is that interface. The processes -may be separated in time (one after the other), in space (running on -different machines) or even be parts of the same process communicating -with itself. - -We can demonstrate this. Observe how small the byte string needed to -capture the reference is. Also note that since this is the same -process, the identical object is found and returned: - -.. doctest:: - - >>> import sys - >>> import pickle - >>> class Foo(object): - ... pass - >>> sys.modules__name__.Foo = Foo # XXX, see below - >>> pickled_byte_string = pickle.dumps(Foo, 0) - >>> len(pickled_byte_string) - 21 - >>> imported = pickle.loads(pickled_byte_string) - >>> imported == Foo - True - >>> imported is Foo - True - >>> class IFoo(zope.interface.Interface): - ... pass - >>> sys.modules__name__.IFoo = IFoo # XXX, see below - >>> pickled_byte_string = pickle.dumps(IFoo, 0) - >>> len(pickled_byte_string) - 22 - >>> imported = pickle.loads(pickled_byte_string) - >>> imported is IFoo - True - >>> imported == IFoo - True - -.. rubric:: References to Global Objects - -The eagle-eyed reader will have noticed the two funny lines like -``sys.modules__name__.Foo = Foo``. What's that for? To understand, -we must know a bit about how Python "pickles" (``pickle.dump`` or -``pickle.dumps``) classes or interfaces. - -When Python pickles a class or an interface, it does so as a "global -object" #global_object_. Global objects are expected to already -exist (contrast this with pickling a string or an object instance, -which creates a new object in the receiving process) with all their -necessary state information (for classes and interfaces, the state -information would be things like the list of methods and defined -attributes) in the receiving process, so the pickled byte string needs -only contain enough data to look up that existing object; this data is a -*reference*. Not only does this minimize the amount of data required -to persist such an object, it also facilitates changing the definition -of the object over time: if a class or interface gains or loses -methods or attributes, loading a previously pickled reference will use -the *current definition* of the object. - -The *reference* to a global object that's stored in the byte string -consists only of the object's ``__name__`` and ``__module__``. Before -a global object *obj* is pickled, Python makes sure that the object being -pickled is the same one that can be found at -``getattr(sys.modulesobj.__module__, obj.__name__)``; if there is no -such object, or it refers to a different object, pickling fails. The -two funny lines make sure that holds, no matter how this example is -run (using some doctest runners, it doesn't hold by default, unlike it -normally would). - -We can show some examples of what happens when that condition doesn't -hold. First, what if we change the global object and try to pickle the -old one? - -.. doctest:: - - >>> sys.modules__name__.Foo = 42 - >>> pickle.dumps(Foo) - Traceback (most recent call last): - ... - _pickle.PicklingError: Can't pickle <class 'Foo'>: it's not the same object as builtins.Foo - -A consequence of this is that only one object of the given name can be -defined and pickled at a time. If we were to try to define a new ``Foo`` -class (remembering that normally the ``sys.modules__name__.Foo =`` -line is automatic), we still cannot pickle the old one: - -.. doctest:: - - >>> orig_Foo = Foo - >>> class Foo(object): - ... pass - >>> sys.modules__name__.Foo = Foo # XXX, usually automatic - >>> pickle.dumps(orig_Foo) - Traceback (most recent call last): - ... - _pickle.PicklingError: Can't pickle <class 'Foo'>: it's not the same object as builtins.Foo - -Or what if there simply is no global object? - -.. doctest:: - - >>> del sys.modules__name__.Foo - >>> pickle.dumps(Foo) - Traceback (most recent call last): - ... - _pickle.PicklingError: Can't pickle <class 'Foo'>: attribute lookup Foo on builtins failed - -Interfaces and classes behave the same in all those ways. - -.. rubric:: What's This Have To Do With Sorting, Equality and Hashing? - -Another important design consideration for interfaces is that they -should be sortable. This permits them to be used, for example, as keys -in a (persistent) `BTree <https://btrees.readthedocs.io>`_. As such, -they define a total ordering, meaning that any given interface can -definitively said to be greater than, less than, or equal to, any -other interface. This relationship must be *stable* and hold the same -across any two processes. - -An object becomes sortable by overriding the equality method -``__eq__`` and at least one of the comparison methods (such as -``__lt__``). - -Classes, on the other hand, are not sortable #class_sort_. -Classes can only be tested for equality, and they implement this using -object identity: ``class_a == class_b`` is equivalent to ``class_a is class_b``. - -In addition to being sortable, it's important for interfaces to be -hashable so they can be used as keys in dictionaries or members of -sets. This is done by implementing the ``__hash__`` method #hashable_. - -Classes are hashable, and they also implement this based on object -identity, with the equivalent of ``id(class_a)``. - -To be both hashable and sortable, the hash method and the equality and -comparison methods **must** `be consistent with each other -<https://docs.python.org/3/reference/datamodel.html#object.__hash__>`_. -That is, they must all be based on the same principle. - -Classes use the principle of identity to implement equality and -hashing, but they don't implement sorting because identity isn't a -stable sorting method (it is different in every process). - -Interfaces need to be sortable. In order for all three of hashing, -equality and sorting to be consistent, interfaces implement them using -the same principle as persistence. Interfaces are treated like "global -objects" and sort and hash using the same information a *reference* to -them would: their ``__name__`` and ``__module__``. - -In this way, hashing, equality and sorting are consistent with each -other, and consistent with pickling: - -.. doctest:: - - >>> class IFoo(zope.interface.Interface): - ... pass - >>> sys.modules__name__.IFoo = IFoo # XXX, usually automatic - >>> f1 = IFoo - >>> pickled_f1 = pickle.dumps(f1) - >>> class IFoo(zope.interface.Interface): - ... pass - >>> sys.modules__name__.IFoo = IFoo # XXX, usually automatic - >>> IFoo == f1 - True - >>> unpickled_f1 = pickle.loads(pickled_f1) - >>> unpickled_f1 == IFoo == f1 - True - -This isn't quite the case for classes; note how ``f1`` wasn't equal to -``Foo`` before pickling, but the unpickled value is: - -.. doctest:: - - >>> class Foo(object): - ... pass - >>> sys.modules__name__.Foo = Foo # XXX, usually automatic - >>> f1 = Foo - >>> pickled_f1 = pickle.dumps(Foo) - >>> class Foo(object): - ... pass - >>> sys.modules__name__.Foo = Foo # XXX, usually automatic - >>> f1 == Foo - False - >>> unpickled_f1 = pickle.loads(pickled_f1) - >>> unpickled_f1 == Foo # Surprise! - True - >>> unpickled_f1 == f1 - False - -For more information, and some rare potential pitfalls, see -:ref:`spec_eq_hash`. - -.. rubric:: Footnotes - -.. #create The main reason we subclass ``Interface`` is to cause the - Python class statement to create an interface, rather - than a class. - - It's possible to create interfaces by calling a special - interface class directly. Doing this, it's possible - (and, on rare occasions, useful) to create interfaces - that don't descend from ``Interface``. Using this - technique is beyond the scope of this document. - -.. #factory Classes are factories. They can be called to create - their instances. We expect that we will eventually - extend the concept of implementation to other kinds of - factories, so that we can declare the interfaces - provided by the objects created. - -.. #compat The goal is substitutability. An object that provides an - extending interface should be substitutable for an object - that provides the extended interface. In our example, an - object that provides ``IBaz`` should be usable wherever an - object that provides ``IBlat`` is expected. - - The interface implementation doesn't enforce this, - but maybe it should do some checks. - -.. #class_sort In Python 2, classes could be sorted, but the sort - was not stable (it also used the identity principle) - and not useful for persistence; this was considered a - bug that was fixed in Python 3. - -.. #hashable In order to be hashable, you must implement both - ``__eq__`` and ``__hash__``. If you only implement - ``__eq__``, Python makes sure the type cannot be - used in a dictionary, set, or with :func:`hash`. In - Python 2, this wasn't the case, and forgetting to - override ``__hash__`` was a constant source of bugs. - -.. #global_object From the name of the pickle bytecode operator; it - varies depending on the protocol but always - includes "GLOBAL".
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/README.ru.rst.txt
Deleted
@@ -1,804 +0,0 @@ -========== -Интерфейсы -========== - -.. contents:: - -Интерфейсы - это объекты специфицирующие (документирующие) внешнее поведение -объектов которые их "предоставляют". Интерфейсы определяют поведение через -следующие составляющие: - -- Неформальную документацию в строках документации - -- Определения атрибутов - -- Инварианты - условия, которые должны соблюдаться для объектов предоставляющих - интерфейс - -Определения атрибутов описывают конкретные атрибуты. Они определяют -имя атрибута и предоставляют документацию и ограничения для значений -атрибута. Определения атрибутов могут быть заданы несколькими путями -как мы увидим ниже. - -Определение интерфейсов -======================= - -Интерфейсы определяются с использованием ключевого слова class:: - - >>> import zope.interface - >>> class IFoo(zope.interface.Interface): - ... """Foo blah blah""" - ... - ... x = zope.interface.Attribute("""X blah blah""") - ... - ... def bar(q, r=None): - ... """bar blah blah""" - -В примере выше мы создали интерфейс `IFoo`. Мы наследуем его от -класса `zope.interface.Interface`, который является родительским интерфейсом -для всех интерфейсов, как `object` - это родительский класс для всех новых -классов #create_. Данный интерфейс не является классом, а является -Интерфейсом, экземпляром `InterfaceClass`:: - - >>> type(IFoo) - <class 'zope.interface.interface.InterfaceClass'> - -Мы можем запросить у интерфейса его документацию:: - - >>> IFoo.__doc__ - 'Foo blah blah' - -и его имя:: - - >>> IFoo.__name__ - 'IFoo' - -и даже модуль в котором он определен:: - - >>> IFoo.__module__ - '__main__' - -Наш интерфейс определяет два атрибута: - -`x` - Это простейшая форма определения атрибутов. Определяются имя - и строка документации. Формально здесь не определяется ничего более. - -`bar` - Это метод. Методы определяются как обычные функции. Метод - это просто - атрибут который должен быть вызываемым с указанием сигнатуры, - предоставляемой определением функции. - - Надо отметить, что аргумент `self` не указывается для `bar`. Интерфейс - документирует как объект *используется*. Когда методы экземпляров классов - вызываются мы не передаем аргумент `self`, таким образом аргумент `self` - не включается и в сигнатуру интерфейса. Аргумент `self` в методах - экземпляров классов на самом деле деталь реализации экземпляров классов - в Python. Другие объекты кроме экземпляров классов могут предоставлять - интерфейсы и их методы могут не быть методами экземпляров классов. Для - примера модули могут предоставлять интерфейсы и их методы обычно просто - функции. Даже экземпляры могут иметь методы не являющиеся методами - экземпляров класса. - -Мы можем получить доступ к атрибутам определенным интерфейсом используя -синтаксис доступа к элементам массива:: - - >>> x = IFoo'x' - >>> type(x) - <class 'zope.interface.interface.Attribute'> - >>> x.__name__ - 'x' - >>> x.__doc__ - 'X blah blah' - - >>> IFoo.get('x').__name__ - 'x' - - >>> IFoo.get('y') - -Можно использовать `in` для определения содержит ли интерфейс -определенное имя:: - - >>> 'x' in IFoo - True - -Мы можем использовать итератор для интерфейсов чтобы получить все имена -которые интерфейсы определяют:: - - >>> names = list(IFoo) - >>> names.sort() - >>> names - 'bar', 'x' - -Надо помнить, что интерфейсы не являются классами. Мы не можем получить -доступ к определениям атрибутов через доступ к атрибутам интерфейсов:: - - >>> IFoo.x - Traceback (most recent call last): - File "<stdin>", line 1, in ? - AttributeError: 'InterfaceClass' object has no attribute 'x' - -Методы также предоставляют доступ к сигнатуре метода:: - - >>> bar = IFoo'bar' - >>> bar.getSignatureString() - '(q, r=None)' - -Объявление интерфейсов -====================== - -Определив интерфейс мы можем теперь *объявить*, что объекты предоставляют их. -Перед описанием деталей определим некоторые термины: - -*предоставлять* - Мы говорим, что объекты *предоставляют* интерфейсы. Если объект - предоставляет интерфейс, тогда интерфейс специфицирует поведение объекта. - Другими словами, интерфейсы специфицируют поведение объектов которые - предоставляют их. - -*реализовать* - Мы обычно говорим что классы *реализуют* интерфейсы. Если класс - реализует интерфейс, тогда экземпляры этого класса предоставляют - данный интерфейс. Объекты предоставляют интерфейсы которые их классы - реализуют #factory_. (Объекты также могут предоставлять интерфейсы напрямую - плюс к тем которые реализуют их классы.) - - Важно помнить, что классы обычно не предоставляют интерфейсы которые - они реализуют. - - Мы можем обобщить это до фабрик. Для любого вызываемого объекта мы можем - объявить что он производит объекты которые предоставляют какие-либо - интерфейсы сказав, что фабрика реализует данные интерфейсы. - -Теперь после того как мы определили эти термины мы можем поговорить об -API для объявления интерфейсов. - -Объявление реализуемых интерфейсов ----------------------------------- - -Наиболее часто используемый путь для объявления интерфейсов - это использование -функции implements в определении класса:: - - >>> class Foo: - ... zope.interface.implements(IFoo) - ... - ... def __init__(self, x=None): - ... self.x = x - ... - ... def bar(self, q, r=None): - ... return q, r, self.x - ... - ... def __repr__(self): - ... return "Foo(%s)" % self.x - -В этом примере мы объявили, что `Foo` реализует `IFoo`. Это значит, что -экземпляры `Foo` предоставляют `IFoo`. После данного объявления есть -несколько путей для анализа объявлений. Во-первых мы можем спросить -что интерфейс реализован классом:: - - >>> IFoo.implementedBy(Foo) - True - -Также мы можем спросить если интерфейс предоставляется объектами класса:: - - >>> foo = Foo() - >>> IFoo.providedBy(foo) - True - -Конечно `Foo` не предоставляет `IFoo`, он реализует его:: - - >>> IFoo.providedBy(Foo) - False - -Мы можем также узнать какие интерфейсы реализуются объектами:: - - >>> list(zope.interface.implementedBy(Foo)) - <InterfaceClass __main__.IFoo> - -Это ошибка спрашивать про интерфейсы реализуемые не вызываемым объектом:: - - >>> IFoo.implementedBy(foo) - Traceback (most recent call last): - ... - TypeError: ('ImplementedBy called for non-factory', Foo(None)) - - >>> list(zope.interface.implementedBy(foo)) - Traceback (most recent call last): - ... - TypeError: ('ImplementedBy called for non-factory', Foo(None)) - -Также можно узнать какие интерфейсы предоставляются объектами:: - - >>> list(zope.interface.providedBy(foo)) - <InterfaceClass __main__.IFoo> - >>> list(zope.interface.providedBy(Foo)) - - -Мы можем объявить интерфейсы реализуемые другими фабриками (кроме классов). -Это можно сделать используя декоратор `implementer` (в стиле Python 2.4). -Для версий Python ниже 2.4 это будет выглядеть следующим образом:: - - >>> def yfoo(y): - ... foo = Foo() - ... foo.y = y - ... return foo - >>> yfoo = zope.interface.implementer(IFoo)(yfoo) - - >>> list(zope.interface.implementedBy(yfoo)) - <InterfaceClass __main__.IFoo> - -Надо заметить, что декоратор implementer может модифицировать свои аргументы. -Вызывающая сторона не должна предполагать, что всегда будет создаваться -новый объект. - -XXX: Double check and update these version numbers, and translate to russian: - -In zope.interface 3.5.1 and lower, the implementer decorator can not -be used for classes, but in 3.5.2 and higher it can:: - - >>> Foo = zope.interface.implementer(IFoo)(Foo) - >>> list(zope.interface.providedBy(Foo())) - <InterfaceClass __main__.IFoo> - -Note that class decorators using the @implementer(IFoo) syntax are only -supported in Python 2.6 and later. - - -Объявление предоставляемых интерфейсов --------------------------------------- - -Мы можем объявлять интерфейсы напрямую предоставляемые объектами. Предположим -что мы хотим документировать что делает метод `__init__` класса `Foo`. Это -*точно* не часть `IFoo`. Обычно мы не должны напрямую вызывать метод `__init__` -для экземпляров Foo. Скорее метод `__init__` является частью метода `__call__` -класса `Foo`:: - - >>> class IFooFactory(zope.interface.Interface): - ... """Create foos""" - ... - ... def __call__(x=None): - ... """Create a foo - ... - ... The argument provides the initial value for x ... - ... """ - -У нас есть класс предоставляющий данный интерфейс, таким образом мы можем -объявить интерфейс класса:: - - >>> zope.interface.directlyProvides(Foo, IFooFactory) - -Теперь мы видим, что Foo уже предоставляет интерфейсы:: - - >>> list(zope.interface.providedBy(Foo)) - <InterfaceClass __main__.IFooFactory> - >>> IFooFactory.providedBy(Foo) - True - -Объявление интерфейсов класса достаточно частая операция и для нее есть -специальная функция объявления `classProvides`, которая позволяет объявлять -интерфейсы при определении класса:: - - >>> class Foo2: - ... zope.interface.implements(IFoo) - ... zope.interface.classProvides(IFooFactory) - ... - ... def __init__(self, x=None): - ... self.x = x - ... - ... def bar(self, q, r=None): - ... return q, r, self.x - ... - ... def __repr__(self): - ... return "Foo(%s)" % self.x - - >>> list(zope.interface.providedBy(Foo2)) - <InterfaceClass __main__.IFooFactory> - >>> IFooFactory.providedBy(Foo2) - True - -Похожая функция `moduleProvides` поддерживает объявление интерфейсов при -определении модуля. Для примера смотрите использование вызова -`moduleProvides` в `zope.interface.__init__`, который объявляет, что -пакет `zope.interface` предоставляет `IInterfaceDeclaration`. - -Иногда мы хотим объявить интерфейсы экземпляров, даже если эти экземпляры -уже берут интерфейсы от своих классов. Предположим, что мы создаем новый -интерфейс `ISpecial`:: - - >>> class ISpecial(zope.interface.Interface): - ... reason = zope.interface.Attribute("Reason why we're special") - ... def brag(): - ... "Brag about being special" - -Мы можем сделать созданный экземпляр foo специальным, предоставив атрибуты -`reason` и `brag`:: - - >>> foo.reason = 'I just am' - >>> def brag(): - ... return "I'm special!" - >>> foo.brag = brag - >>> foo.reason - 'I just am' - >>> foo.brag() - "I'm special!" - -и объявив интерфейс:: - - >>> zope.interface.directlyProvides(foo, ISpecial) - -таким образом новый интерфейс включается в список предоставляемых интерфейсов:: - - >>> ISpecial.providedBy(foo) - True - >>> list(zope.interface.providedBy(foo)) - <InterfaceClass __main__.ISpecial>, <InterfaceClass __main__.IFoo> - -Мы также можем определить, что интерфейсы напрямую предоставляются -объектами:: - - >>> list(zope.interface.directlyProvidedBy(foo)) - <InterfaceClass __main__.ISpecial> - - >>> newfoo = Foo() - >>> list(zope.interface.directlyProvidedBy(newfoo)) - - -Наследуемые объявления ----------------------- - -Обычно объявления наследуются:: - - >>> class SpecialFoo(Foo): - ... zope.interface.implements(ISpecial) - ... reason = 'I just am' - ... def brag(self): - ... return "I'm special because %s" % self.reason - - >>> list(zope.interface.implementedBy(SpecialFoo)) - <InterfaceClass __main__.ISpecial>, <InterfaceClass __main__.IFoo> - - >>> list(zope.interface.providedBy(SpecialFoo())) - <InterfaceClass __main__.ISpecial>, <InterfaceClass __main__.IFoo> - -Иногда мы не хотим наследовать объявления. В этом случае мы можем -использовать `implementsOnly` вместо `implements`:: - - >>> class Special(Foo): - ... zope.interface.implementsOnly(ISpecial) - ... reason = 'I just am' - ... def brag(self): - ... return "I'm special because %s" % self.reason - - >>> list(zope.interface.implementedBy(Special)) - <InterfaceClass __main__.ISpecial> - - >>> list(zope.interface.providedBy(Special())) - <InterfaceClass __main__.ISpecial> - -Внешние объявления ------------------- - -Обычно мы создаем объявления реализации как часть объявления класса. Иногда -мы можем захотеть создать объявления вне объявления класса. Для примера, -мы можем хотеть объявить интерфейсы для классов которые писали не мы. -Для этого может использоваться функция `classImplements`:: - - >>> class C: - ... pass - - >>> zope.interface.classImplements(C, IFoo) - >>> list(zope.interface.implementedBy(C)) - <InterfaceClass __main__.IFoo> - -Мы можем использовать `classImplementsOnly` для исключения наследуемых -интерфейсов:: - - >>> class C(Foo): - ... pass - - >>> zope.interface.classImplementsOnly(C, ISpecial) - >>> list(zope.interface.implementedBy(C)) - <InterfaceClass __main__.ISpecial> - -Объекты объявлений ------------------- - -Когда мы объявляем интерфейсы, мы создаем объект *объявления*. Когда мы -запрашиваем объявления возвращается объект объявления:: - - >>> type(zope.interface.implementedBy(Special)) - <class 'zope.interface.declarations.Implements'> - -Объекты объявления и объекты интерфейсов во многом похожи друг на друга. -На самом деле они даже имеют общий базовый класс. Важно понять, что они могут -использоваться там, где в объявлениях ожидаются интерфейсы. Вот простой -пример:: - - >>> class Special2(Foo): - ... zope.interface.implementsOnly( - ... zope.interface.implementedBy(Foo), - ... ISpecial, - ... ) - ... reason = 'I just am' - ... def brag(self): - ... return "I'm special because %s" % self.reason - -Объявление здесь практически такое же как -``zope.interface.implements(ISpecial)``, отличие только в порядке -интерфейсов в итоговом объявления:: - - >>> list(zope.interface.implementedBy(Special2)) - <InterfaceClass __main__.IFoo>, <InterfaceClass __main__.ISpecial> - -Наследование интерфейсов -======================== - -Интерфейсы могут расширять другие интерфейсы. Они делают это просто -показывая эти интерфейсы как базовые:: - - >>> class IBlat(zope.interface.Interface): - ... """Blat blah blah""" - ... - ... y = zope.interface.Attribute("y blah blah") - ... def eek(): - ... """eek blah blah""" - - >>> IBlat.__bases__ - (<InterfaceClass zope.interface.Interface>,) - - >>> class IBaz(IFoo, IBlat): - ... """Baz blah""" - ... def eek(a=1): - ... """eek in baz blah""" - ... - - >>> IBaz.__bases__ - (<InterfaceClass __main__.IFoo>, <InterfaceClass __main__.IBlat>) - - >>> names = list(IBaz) - >>> names.sort() - >>> names - 'bar', 'eek', 'x', 'y' - -Заметим, что `IBaz` переопределяет eek:: - - >>> IBlat'eek'.__doc__ - 'eek blah blah' - >>> IBaz'eek'.__doc__ - 'eek in baz blah' - -Мы были осторожны, переопределяя eek совместимым путем. Когда интерфейс -расширяется, расширенный интерфейс должен быть совместимым #compat_ с -расширяемыми интерфейсами. - -Мы можем запросить расширяет ли один из интерфейсов другой:: - - >>> IBaz.extends(IFoo) - True - >>> IBlat.extends(IFoo) - False - -Заметим, что интерфейсы не расширяют сами себя:: - - >>> IBaz.extends(IBaz) - False - -Если мы хотим видеть, что интерфейс расширяет сам себя,то мы можем использовать `isOrExtends`:: - - >>> IBaz.isOrExtends(IBaz) - True - >>> IBaz.isOrExtends(IFoo) - True - >>> IFoo.isOrExtends(IBaz) - False - -Когда мы применяем итерацию к интерфейсу мы получаем все имена которые он -определяет, включая имена определенные для базовых интерфейсов. Иногда -мы хотим получить *только* имена определенные интерфейсом напрямую. -Для этого мы используем метод `names`:: - - >>> list(IBaz.names()) - 'eek' - -Наследование в случае определения атрибутов --------------------------------------------- - -Интерфейс может переопределять определения атрибутов из базовых интерфейсов. -Если два базовых интерфейса определяют один и тот же атрибут, то данный атрибут -наследуется от более специфичного интерфейса. Для примера:: - - >>> class IBase(zope.interface.Interface): - ... - ... def foo(): - ... "base foo doc" - - >>> class IBase1(IBase): - ... pass - - >>> class IBase2(IBase): - ... - ... def foo(): - ... "base2 foo doc" - - >>> class ISub(IBase1, IBase2): - ... pass - -Определение ISub для foo будет из IBase2 т.к. IBase2 более специфичен для -IBase:: - - >>> ISub'foo'.__doc__ - 'base2 foo doc' - -Заметим, что это отличается от поиска в глубину. - -Иногда полезно узнать, что интерфейс определяет атрибут напрямую. Мы можем -использовать метод `direct` для получения напрямую определенных атрибутов:: - - >>> IBase.direct('foo').__doc__ - 'base foo doc' - - >>> ISub.direct('foo') - -Спецификации ------------- - -Интерфейсы и объявления - это специальные случаи спецификаций. Описание -выше для наследования интерфейсов можно применить и к объявлениям и -к спецификациям. Объявления фактически расширяют интерфейсы которые они -объявляют:: - - >>> class Baz(object): - ... zope.interface.implements(IBaz) - - >>> baz_implements = zope.interface.implementedBy(Baz) - >>> baz_implements.__bases__ - (<InterfaceClass __main__.IBaz>, <implementedBy ...object>) - - >>> baz_implements.extends(IFoo) - True - - >>> baz_implements.isOrExtends(IFoo) - True - >>> baz_implements.isOrExtends(baz_implements) - True - -Спецификации (интерфейсы и объявления) предоставляют атрибут `__sro__` -который описывает спецификацию и всех ее предков:: - - >>> baz_implements.__sro__ - (<implementedBy __main__.Baz>, - <InterfaceClass __main__.IBaz>, - <InterfaceClass __main__.IFoo>, - <InterfaceClass __main__.IBlat>, - <InterfaceClass zope.interface.Interface>, - <implementedBy ...object>) - -Помеченные значения -=================== - -Интерфейсы и описания атрибутов поддерживают механизм расширения, -заимствованный из UML и называемый "помеченные значения", который позволяет -сохранять дополнительные данные:: - - >>> IFoo.setTaggedValue('date-modified', '2004-04-01') - >>> IFoo.setTaggedValue('author', 'Jim Fulton') - >>> IFoo.getTaggedValue('date-modified') - '2004-04-01' - >>> IFoo.queryTaggedValue('date-modified') - '2004-04-01' - >>> IFoo.queryTaggedValue('datemodified') - >>> tags = list(IFoo.getTaggedValueTags()) - >>> tags.sort() - >>> tags - 'author', 'date-modified' - -Атрибуты функций конвертируются в помеченные значения, когда создаются -определения атрибутов метода:: - - >>> class IBazFactory(zope.interface.Interface): - ... def __call__(): - ... "create one" - ... __call__.return_type = IBaz - - >>> IBazFactory'__call__'.getTaggedValue('return_type') - <InterfaceClass __main__.IBaz> - -Помеченные значения также могут быть определены внутри определения -интерфейса:: - - >>> class IWithTaggedValues(zope.interface.Interface): - ... zope.interface.taggedValue('squish', 'squash') - >>> IWithTaggedValues.getTaggedValue('squish') - 'squash' - -Инварианты -========== - -Интерфейсы могут описывать условия, которые должны быть соблюдены для объектов, -которые их предоставляют. Эти условия описываются одним или несколькими -инвариантами. Инварианты - это вызываемые объекты, которые будут вызваны -с объектом, предоставляющим интерфейс в качестве параметра. Инвариант -должен выкинуть исключение `Invalid` если условие не соблюдено. Например:: - - >>> class RangeError(zope.interface.Invalid): - ... """A range has invalid limits""" - ... def __repr__(self): - ... return "RangeError(%r)" % self.args - - >>> def range_invariant(ob): - ... if ob.max < ob.min: - ... raise RangeError(ob) - -Определив этот инвариант, мы можем использовать его в определении интерфейсов:: - - >>> class IRange(zope.interface.Interface): - ... min = zope.interface.Attribute("Lower bound") - ... max = zope.interface.Attribute("Upper bound") - ... - ... zope.interface.invariant(range_invariant) - -Интерфейсы имеют метод для проверки своих инвариантов:: - - >>> class Range(object): - ... zope.interface.implements(IRange) - ... - ... def __init__(self, min, max): - ... self.min, self.max = min, max - ... - ... def __repr__(self): - ... return "Range(%s, %s)" % (self.min, self.max) - - >>> IRange.validateInvariants(Range(1,2)) - >>> IRange.validateInvariants(Range(1,1)) - >>> IRange.validateInvariants(Range(2,1)) - Traceback (most recent call last): - ... - RangeError: Range(2, 1) - -В случае нескольких инвариантов мы можем захотеть остановить проверку после -первой ошибки. Если мы передадим в `validateInvariants` пустой список, тогда -будет выкинуто единственное исключение `Invalid` со списком исключений -как аргументом:: - - >>> from zope.interface.exceptions import Invalid - >>> errors = - >>> try: - ... IRange.validateInvariants(Range(2,1), errors) - ... except Invalid, e: - ... str(e) - 'RangeError(Range(2, 1))' - -И список будет заполнен индивидуальными исключениями:: - - >>> errors - RangeError(Range(2, 1)) - - >>> del errors: - -Адаптация -========= - -Интерфейсы могут быть вызваны для осуществления адаптации. Эта семантика -основана на функции adapt из PEP 246. Если объект не может быть адаптирован, -будет выкинут TypeError:: - - >>> class I(zope.interface.Interface): - ... pass - - >>> I(0) - Traceback (most recent call last): - ... - TypeError: ('Could not adapt', 0, <InterfaceClass __main__.I>) - -только если альтернативное значение не передано как второй аргумент:: - - >>> I(0, 'bob') - 'bob' - -Если объект уже реализует нужный интерфейс, он будет возвращен:: - - >>> class C(object): - ... zope.interface.implements(I) - - >>> obj = C() - >>> I(obj) is obj - True - -Если объект реализует __conform__, тогда она будет использована:: - - >>> class C(object): - ... zope.interface.implements(I) - ... def __conform__(self, proto): - ... return 0 - - >>> I(C()) - 0 - -Также если присутствуют функции для вызова адаптации (см. __adapt__) они будут -использованы:: - - >>> from zope.interface.interface import adapter_hooks - >>> def adapt_0_to_42(iface, obj): - ... if obj == 0: - ... return 42 - - >>> adapter_hooks.append(adapt_0_to_42) - >>> I(0) - 42 - - >>> adapter_hooks.remove(adapt_0_to_42) - >>> I(0) - Traceback (most recent call last): - ... - TypeError: ('Could not adapt', 0, <InterfaceClass __main__.I>) - - -__adapt__ ---------- - -:: - - >>> class I(zope.interface.Interface): - ... pass - -Интерфейсы реализуют метод __adapt__ из PEP 246. Этот метод обычно не -вызывается напрямую. Он вызывается архитектурой адаптации из PEP 246 и методом -__call__ интерфейсов. Метод адаптации отвечает за адаптацию объекта к -получателю. Версия по умолчанию возвращает `None`:: - - >>> I.__adapt__(0) - -если только переданный объект не предоставляет нужный интерфейс:: - - >>> class C(object): - ... zope.interface.implements(I) - - >>> obj = C() - >>> I.__adapt__(obj) is obj - True - -Функции для вызова адаптации могут быть добавлены (или удалены) для -предоставления адаптации "на заказ". Мы установим глупую функцию которая -адаптирует 0 к 42. Мы устанавливаем функцию просто добавляя ее к списку -`adapter_hooks`:: - - >>> from zope.interface.interface import adapter_hooks - >>> def adapt_0_to_42(iface, obj): - ... if obj == 0: - ... return 42 - - >>> adapter_hooks.append(adapt_0_to_42) - >>> I.__adapt__(0) - 42 - -Функции должны возвращать либо адаптер, либо `None`, если адаптер не найден. -Функции могут быть удалены удалением их из списка:: - - >>> adapter_hooks.remove(adapt_0_to_42) - >>> I.__adapt__(0) - - -.. #create Основная причина по которой мы наследуемся от `Interface` - это - что бы быть уверенными в том, что ключевое слово class будет - создавать интерфейс, а не класс. - - Есть возможность создать интерфейсы вызвав специальный - класс интерфейса напрямую. Делая это, возможно (и в редких - случаях полезно) создать интерфейсы которые не наследуются - от `Interface`. Однако использование этой техники выходит - за рамки данного документа. - -.. #factory Классы - это фабрики. Они могут быть вызваны для создания - своих экземпляров. Мы ожидаем что в итоге мы расширим - концепцию реализации на другие типы фабрик, таким образом - мы сможем объявлять интерфейсы предоставляемые созданными - фабриками объектами. - -.. #compat Цель - заменяемость. Объект который предоставляет расширенный - интерфейс должен быть заменяем в качестве объектов которые - предоставляют расширяемый интерфейс. В нашем примере объект - который предоставляет IBaz должен быть используемым и - в случае если ожидается объект который предоставляет IBlat. - - Реализация интерфейса не требует этого. Но возможно в дальнейшем - она должна будет делать какие-либо проверки.
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/adapter.rst.txt
Deleted
@@ -1,690 +0,0 @@ -.. _adapter-registry: - -================== - Adapter Registry -================== - -Adapter registries provide a way to register objects that depend on -one or more interface specifications and provide (perhaps indirectly) -some interface. In addition, the registrations have names. (You can -think of the names as qualifiers of the provided interfaces.) - -The term "interface specification" refers both to interfaces and to -interface declarations, such as declarations of interfaces implemented -by a class. - - -Single Adapters -=============== - -Let's look at a simple example, using a single required specification: - -.. doctest:: - - >>> from zope.interface.adapter import AdapterRegistry - >>> import zope.interface - - >>> class IRequireBase(zope.interface.Interface): - ... pass - >>> class IProvideBase(zope.interface.Interface): - ... pass - >>> class IProvideChild(IProvideBase): - ... pass - - >>> registry = AdapterRegistry() - -We'll register an object that depends on ``IRequireBase`` and "provides" ``IProvideChild``: - -.. doctest:: - - >>> registry.register(IRequireBase, IProvideChild, '', 'Base->Child') - -Given the registration, we can look it up again: - -.. doctest:: - - >>> registry.lookup(IRequireBase, IProvideChild, '') - 'Base->Child' - -Note that we used an integer in the example. In real applications, -one would use some objects that actually depend on or provide -interfaces. The registry doesn't care about what gets registered, so -we'll use integers and strings to keep the examples simple. There is -one exception. Registering a value of ``None`` unregisters any -previously-registered value. - -If an object depends on a specification, it can be looked up with a -specification that extends the specification that it depends on: - -.. doctest:: - - >>> class IRequireChild(IRequireBase): - ... pass - >>> registry.lookup(IRequireChild, IProvideChild, '') - 'Base->Child' - -We can use a class implementation specification to look up the object: - -.. doctest:: - - >>> @zope.interface.implementer(IRequireChild) - ... class C2: - ... pass - - >>> registry.lookup(zope.interface.implementedBy(C2), IProvideChild, '') - 'Base->Child' - - -and it can be looked up for interfaces that its provided interface -extends: - -.. doctest:: - - >>> registry.lookup(IRequireBase, IProvideBase, '') - 'Base->Child' - >>> registry.lookup(IRequireChild, IProvideBase, '') - 'Base->Child' - -But if you require a specification that doesn't extend the specification the -object depends on, you won't get anything: - -.. doctest:: - - >>> registry.lookup(zope.interface.Interface, IProvideBase, '') - -By the way, you can pass a default value to lookup: - -.. doctest:: - - >>> registry.lookup(zope.interface.Interface, IProvideBase, '', 42) - 42 - -If you try to get an interface the object doesn't provide, you also -won't get anything: - -.. doctest:: - - >>> class IProvideGrandchild(IProvideChild): - ... pass - >>> registry.lookup(IRequireBase, IProvideGrandchild, '') - -You also won't get anything if you use the wrong name: - -.. doctest:: - - >>> registry.lookup(IRequireBase, IProvideBase, 'bob') - >>> registry.register(IRequireBase, IProvideChild, 'bob', "Bob's 12") - >>> registry.lookup(IRequireBase, IProvideBase, 'bob') - "Bob's 12" - -You can leave the name off when doing a lookup: - -.. doctest:: - - >>> registry.lookup(IRequireBase, IProvideBase) - 'Base->Child' - -If we register an object that provides ``IProvideBase``: - -.. doctest:: - - >>> registry.register(IRequireBase, IProvideBase, '', 'Base->Base') - -then that object will be preferred over ``O('Base->Child')``: - -.. doctest:: - - >>> registry.lookup(IRequireBase, IProvideBase, '') - 'Base->Base' - -Also, if we register an object for ``IRequireChild``, then that will be preferred -when using ``IRequireChild``: - -.. doctest:: - - >>> registry.register(IRequireChild, IProvideBase, '', 'Child->Base') - >>> registry.lookup(IRequireChild, IProvideBase, '') - 'Child->Base' - -Finding out what, if anything, is registered --------------------------------------------- - -We can ask if there is an adapter registered for a collection of -interfaces. This is different than lookup, because it looks for an -exact match: - -.. doctest:: - - >>> print(registry.registered(IRequireBase, IProvideBase)) - Base->Base - - >>> print(registry.registered(IRequireBase, IProvideChild)) - Base->Child - - >>> print(registry.registered(IRequireBase, IProvideChild, 'bob')) - Bob's 12 - - - >>> print(registry.registered(IRequireChild, IProvideBase)) - Child->Base - - >>> print(registry.registered(IRequireChild, IProvideChild)) - None - -In the last example, ``None`` was returned because nothing was registered -exactly for the given interfaces. - -lookup1 -------- - -Lookup of single adapters is common enough that there is a specialized -version of lookup that takes a single required interface: - -.. doctest:: - - >>> registry.lookup1(IRequireChild, IProvideBase, '') - 'Child->Base' - >>> registry.lookup1(IRequireChild, IProvideBase) - 'Child->Base' - -Actual Adaptation ------------------ - -The adapter registry is intended to support adaptation, where one -object that implements an interface is adapted to another object that -supports a different interface. The adapter registry supports the -computation of adapters. In this case, we have to register adapter -factories: - -.. doctest:: - - >>> class IR(zope.interface.Interface): - ... pass - - >>> @zope.interface.implementer(IR) - ... class X(object): - ... pass - - >>> @zope.interface.implementer(IProvideBase) - ... class Y(object): - ... def __init__(self, context): - ... self.context = context - - >>> registry.register(IR, IProvideBase, '', Y) - -In this case, we registered a class as the factory. Now we can call -``queryAdapter`` to get the adapted object: - -.. doctest:: - - >>> x = X() - >>> y = registry.queryAdapter(x, IProvideBase) - >>> y.__class__.__name__ - 'Y' - >>> y.context is x - True - -We can register and lookup by name too: - -.. doctest:: - - >>> class Y2(Y): - ... pass - - >>> registry.register(IR, IProvideBase, 'bob', Y2) - >>> y = registry.queryAdapter(x, IProvideBase, 'bob') - >>> y.__class__.__name__ - 'Y2' - >>> y.context is x - True - -Passing ``super`` objects works as expected to find less specific adapters: - -.. doctest:: - - >>> class IDerived(IR): - ... pass - >>> @zope.interface.implementer(IDerived) - ... class Derived(X): - ... pass - >>> class DerivedAdapter(Y): - ... def query_next(self): - ... return registry.queryAdapter( - ... super(type(self.context), self.context), - ... IProvideBase) - >>> registry.register(IDerived, IProvideBase, '', DerivedAdapter) - >>> derived = Derived() - >>> adapter = registry.queryAdapter(derived, IProvideBase) - >>> adapter.__class__.__name__ - 'DerivedAdapter' - >>> adapter = adapter.query_next() - >>> adapter.__class__.__name__ - 'Y' - -When the adapter factory produces ``None``, then this is treated as if no -adapter has been found. This allows us to prevent adaptation (when desired) -and let the adapter factory determine whether adaptation is possible based on -the state of the object being adapted: - -.. doctest:: - - >>> def factory(context): - ... if context.name == 'object': - ... return 'adapter' - ... return None - - >>> @zope.interface.implementer(IR) - ... class Object(object): - ... name = 'object' - - >>> registry.register(IR, IProvideBase, 'conditional', factory) - >>> obj = Object() - >>> registry.queryAdapter(obj, IProvideBase, 'conditional') - 'adapter' - >>> obj.name = 'no object' - >>> registry.queryAdapter(obj, IProvideBase, 'conditional') is None - True - >>> registry.queryAdapter(obj, IProvideBase, 'conditional', 'default') - 'default' - -An alternate method that provides the same function as ``queryAdapter()`` is -`adapter_hook()`: - -.. doctest:: - - >>> y = registry.adapter_hook(IProvideBase, x) - >>> y.__class__.__name__ - 'Y' - >>> y.context is x - True - >>> y = registry.adapter_hook(IProvideBase, x, 'bob') - >>> y.__class__.__name__ - 'Y2' - >>> y.context is x - True - -The ``adapter_hook()`` simply switches the order of the object and -interface arguments. It is used to hook into the interface call -mechanism. - - -Default Adapters ----------------- - -Sometimes, you want to provide an adapter that will adapt anything. -For that, provide ``None`` as the required interface: - -.. doctest:: - - >>> registry.register(None, IProvideBase, '', 1) - -then we can use that adapter for interfaces we don't have specific -adapters for: - -.. doctest:: - - >>> class IQ(zope.interface.Interface): - ... pass - >>> registry.lookup(IQ, IProvideBase, '') - 1 - -Of course, specific adapters are still used when applicable: - -.. doctest:: - - >>> registry.lookup(IRequireChild, IProvideBase, '') - 'Child->Base' - - -Class adapters --------------- - -You can register adapters for class declarations, which is almost the -same as registering them for a class: - -.. doctest:: - - >>> registry.register(zope.interface.implementedBy(C2), IProvideBase, '', 'C21') - >>> registry.lookup(zope.interface.implementedBy(C2), IProvideBase, '') - 'C21' - -Dict adapters -------------- - -At some point it was impossible to register dictionary-based adapters due a -bug. Let's make sure this works now: - -.. doctest:: - - >>> adapter = {} - >>> registry.register((), IQ, '', adapter) - >>> registry.lookup((), IQ, '') is adapter - True - -Unregistering -------------- - -You can unregister by registering ``None``, rather than an object: - -.. doctest:: - - >>> registry.register(zope.interface.implementedBy(C2), IProvideBase, '', None) - >>> registry.lookup(zope.interface.implementedBy(C2), IProvideBase, '') - 'Child->Base' - -Of course, this means that ``None`` can't be registered. This is an -exception to the statement, made earlier, that the registry doesn't -care what gets registered. - -Multi-adapters -============== - -You can adapt multiple specifications: - -.. doctest:: - - >>> registry.register(IRequireBase, IQ, IProvideChild, '', '1q2') - >>> registry.lookup(IRequireBase, IQ, IProvideChild, '') - '1q2' - >>> registry.lookup(IRequireChild, IQ, IProvideBase, '') - '1q2' - - >>> class IS(zope.interface.Interface): - ... pass - >>> registry.lookup(IRequireChild, IS, IProvideBase, '') - - >>> class IQ2(IQ): - ... pass - - >>> registry.lookup(IRequireChild, IQ2, IProvideBase, '') - '1q2' - - >>> registry.register(IRequireBase, IQ2, IProvideChild, '', '(Base,Q2)->Child') - >>> registry.lookup(IRequireChild, IQ2, IProvideBase, '') - '(Base,Q2)->Child' - -Multi-adaptation ----------------- - -You can adapt multiple objects: - -.. doctest:: - - >>> @zope.interface.implementer(IQ) - ... class Q: - ... pass - -As with single adapters, we register a factory, which is often a class: - -.. doctest:: - - >>> class IM(zope.interface.Interface): - ... pass - >>> @zope.interface.implementer(IM) - ... class M: - ... def __init__(self, x, q): - ... self.x, self.q = x, q - >>> registry.register(IR, IQ, IM, '', M) - -And then we can call ``queryMultiAdapter`` to compute an adapter: - -.. doctest:: - - >>> q = Q() - >>> m = registry.queryMultiAdapter((x, q), IM) - >>> m.__class__.__name__ - 'M' - >>> m.x is x and m.q is q - True - -and, of course, we can use names: - -.. doctest:: - - >>> class M2(M): - ... pass - >>> registry.register(IR, IQ, IM, 'bob', M2) - >>> m = registry.queryMultiAdapter((x, q), IM, 'bob') - >>> m.__class__.__name__ - 'M2' - >>> m.x is x and m.q is q - True - -Default Adapters ----------------- - -As with single adapters, you can define default adapters by specifying -``None`` for the *first* specification: - -.. doctest:: - - >>> registry.register(None, IQ, IProvideChild, '', '(None,Q)->Child') - >>> registry.lookup(IS, IQ, IProvideChild, '') - '(None,Q)->Child' - -Null Adapters -============= - -You can also adapt **no** specification: - -.. doctest:: - - >>> registry.register(, IProvideChild, '', '->Child') - >>> registry.lookup(, IProvideChild, '') - '->Child' - >>> registry.lookup(, IProvideBase, '') - '->Child' - -Listing named adapters ----------------------- - -Adapters are named. Sometimes, it's useful to get all of the named -adapters for given interfaces: - -.. doctest:: - - >>> adapters = list(registry.lookupAll(IRequireBase, IProvideBase)) - >>> adapters.sort() - >>> assert adapters == (u'', 'Base->Base'), (u'bob', "Bob's 12") - -This works for multi-adapters too: - -.. doctest:: - - >>> registry.register(IRequireBase, IQ2, IProvideChild, 'bob', '(Base,Q2)->Child for bob') - >>> adapters = list(registry.lookupAll(IRequireChild, IQ2, IProvideBase)) - >>> adapters.sort() - >>> assert adapters == (u'', '(Base,Q2)->Child'), (u'bob', '(Base,Q2)->Child for bob') - -And even null adapters: - -.. doctest:: - - >>> registry.register(, IProvideChild, 'bob', 3) - >>> adapters = list(registry.lookupAll(, IProvideBase)) - >>> adapters.sort() - >>> assert adapters == (u'', '->Child'), (u'bob', 3) - -Subscriptions -============= - -Normally, we want to look up an object that most closely matches a -specification. Sometimes, we want to get all of the objects that -match some specification. We use *subscriptions* for this. We -subscribe objects against specifications and then later find all of -the subscribed objects: - -.. doctest:: - - >>> registry.subscribe(IRequireBase, IProvideChild, 'Base->Child (1)') - >>> registry.subscriptions(IRequireBase, IProvideChild) - 'Base->Child (1)' - -Note that, unlike regular adapters, subscriptions are unnamed. - -You can have multiple subscribers for the same specification: - -.. doctest:: - - >>> registry.subscribe(IRequireBase, IProvideChild, 'Base->Child (2)') - >>> registry.subscriptions(IRequireBase, IProvideChild) - 'Base->Child (1)', 'Base->Child (2)' - -If subscribers are registered for the same required interfaces, they -are returned in the order of definition. - -You can register subscribers for all specifications using ``None``: - -.. doctest:: - - >>> registry.subscribe(None, IProvideBase, 'None->Base') - >>> registry.subscriptions(IRequireChild, IProvideBase) - 'None->Base', 'Base->Child (1)', 'Base->Child (2)' - -Note that the new subscriber is returned first. - -Subscribers defined for less specific required interfaces are returned -before subscribers for more specific interfaces: - -.. doctest:: - - >>> class IRequireGrandchild(IRequireChild): - ... pass - >>> registry.subscribe(IRequireChild, IProvideBase, 'Child->Base') - >>> registry.subscribe(IRequireGrandchild, IProvideBase, 'Grandchild->Base') - >>> registry.subscriptions(IRequireGrandchild, IProvideBase) - 'None->Base', 'Base->Child (1)', 'Base->Child (2)', 'Child->Base', 'Grandchild->Base' - -Subscriptions may be combined over multiple compatible specifications: - -.. doctest:: - - >>> registry.subscriptions(IRequireChild, IProvideBase) - 'None->Base', 'Base->Child (1)', 'Base->Child (2)', 'Child->Base' - >>> registry.subscribe(IRequireBase, IProvideBase, 'Base->Base') - >>> registry.subscriptions(IRequireChild, IProvideBase) - 'None->Base', 'Base->Child (1)', 'Base->Child (2)', 'Base->Base', 'Child->Base' - >>> registry.subscribe(IRequireChild, IProvideChild, 'Child->Child') - >>> registry.subscriptions(IRequireChild, IProvideBase) - 'None->Base', 'Base->Child (1)', 'Base->Child (2)', 'Base->Base', 'Child->Child', 'Child->Base' - >>> registry.subscriptions(IRequireChild, IProvideChild) - 'Base->Child (1)', 'Base->Child (2)', 'Child->Child' - -Subscriptions can be on multiple specifications: - -.. doctest:: - - >>> registry.subscribe(IRequireBase, IQ, IProvideChild, '(Base,Q)->Child') - >>> registry.subscriptions(IRequireBase, IQ, IProvideChild) - '(Base,Q)->Child' - -As with single subscriptions and non-subscription adapters, you can -specify ``None`` for the first required interface, to specify a default: - -.. doctest:: - - >>> registry.subscribe(None, IQ, IProvideChild, '(None,Q)->Child') - >>> registry.subscriptions(IS, IQ, IProvideChild) - '(None,Q)->Child' - >>> registry.subscriptions(IRequireBase, IQ, IProvideChild) - '(None,Q)->Child', '(Base,Q)->Child' - -You can have subscriptions that are independent of any specifications: - -.. doctest:: - - >>> list(registry.subscriptions(, IProvideBase)) - - - >>> registry.subscribe(, IProvideChild, 'sub2') - >>> registry.subscriptions(, IProvideBase) - 'sub2' - >>> registry.subscribe(, IProvideBase, 'sub1') - >>> registry.subscriptions(, IProvideBase) - 'sub2', 'sub1' - >>> registry.subscriptions(, IProvideChild) - 'sub2' - -Unregistering subscribers -------------------------- - -We can unregister subscribers. When unregistering a subscriber, we -can unregister a *specific* subscriber: - -.. doctest:: - - >>> registry.unsubscribe(IRequireBase, IProvideBase, 'Base->Base') - >>> registry.subscriptions(IRequireBase, IProvideBase) - 'None->Base', 'Base->Child (1)', 'Base->Child (2)' - -If we don't specify a value, then *all* subscribers matching the given -interfaces will be unsubscribed: - -.. doctest:: - - >>> registry.unsubscribe(IRequireBase, IProvideChild) - >>> registry.subscriptions(IRequireBase, IProvideBase) - 'None->Base' - - -Subscription adapters ---------------------- - -We normally register adapter factories, which then allow us to compute -adapters, but with subscriptions, we get multiple adapters. Here's an -example of multiple-object subscribers: - -.. doctest:: - - >>> registry.subscribe(IR, IQ, IM, M) - >>> registry.subscribe(IR, IQ, IM, M2) - - >>> subscribers = registry.subscribers((x, q), IM) - >>> len(subscribers) - 2 - >>> class_names = s.__class__.__name__ for s in subscribers - >>> class_names.sort() - >>> class_names - 'M', 'M2' - >>> (s.x is x and s.q is q) for s in subscribers - True, True - -Adapter factory subscribers can't return ``None`` values: - -.. doctest:: - - >>> def M3(x, y): - ... return None - - >>> registry.subscribe(IR, IQ, IM, M3) - >>> subscribers = registry.subscribers((x, q), IM) - >>> len(subscribers) - 2 - -Handlers --------- - -A handler is a subscriber factory that doesn't produce any normal -output. It returns ``None``. A handler is unlike adapters in that it does -all of its work when the factory is called. - -To register a handler, simply provide ``None`` as the provided interface: - -.. doctest:: - - >>> def handler(event): - ... print('handler', event) - - >>> registry.subscribe(IRequireBase, None, handler) - >>> registry.subscriptions(IRequireBase, None) == handler - True - - -Components -========== - -A :class:`zope.interface.registry.Components` object implements the -:class:`zope.interface.interfaces.IComponents` interface. This -interface uses multiple adapter registries to implement multiple -higher-level concerns (utilities, adapters and handlers), while also -providing event notifications and query capabilities.
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/adapter.ru.rst.txt
Deleted
@@ -1,540 +0,0 @@ -================ -Реестр адаптеров -================ - -.. contents:: - -Реестры адаптеров предоставляют возможность для регистрации объектов которые -зависят от одной, или нескольких спецификаций интерфейсов и предоставляют -(возможно не напрямую) какой-либо интерфейс. В дополнение, регистрации имеют -имена. (Можно думать об именах как о спецификаторах предоставляемого -интерфейса.) - -Термин "спецификация интерфейса" ссылается и на интерфейсы и на определения -интерфейсов, такие как определения интерфейсов реализованных некоторым классом. - -Одиночные адаптеры -================== - -Давайте рассмотрим простой пример использующий единственную требуемую -спецификацию:: - - >>> from zope.interface.adapter import AdapterRegistry - >>> import zope.interface - - >>> class IR1(zope.interface.Interface): - ... pass - >>> class IP1(zope.interface.Interface): - ... pass - >>> class IP2(IP1): - ... pass - - >>> registry = AdapterRegistry() - -Мы зарегистрируем объект который зависит от IR1 и "предоставляет" IP2:: - - >>> registry.register(IR1, IP2, '', 12) - -После регистрации мы можем запросить объект снова:: - - >>> registry.lookup(IR1, IP2, '') - 12 - -Заметьте, что мы используем целое в этом примере. В реальных приложениях вы -можете использовать объекты которые на самом деле зависят или предоставляют -интерфейсы. Реестр не заботиться о том, что регистрируется и таким образом мы -можем использовать целые, или строки что бы упростить наши примеры. Здесь есть -одно исключение. Регистрация значения None удаляет регистрацию для любого -зарегистрированного прежде значения. - -Если объект зависит от спецификации он может быть запрошен с помощью -спецификации которая расширяет спецификацию от которой он зависит:: - - >>> class IR2(IR1): - ... pass - >>> registry.lookup(IR2, IP2, '') - 12 - -Мы можем использовать класс реализующий спецификацию для запроса объекта:: - - >>> class C2: - ... zope.interface.implements(IR2) - - >>> registry.lookup(zope.interface.implementedBy(C2), IP2, '') - 12 - -и объект может быть запрошен для интерфейсов которые предоставляемый объектом -интерфейс расширяет:: - - >>> registry.lookup(IR1, IP1, '') - 12 - >>> registry.lookup(IR2, IP1, '') - 12 - -Но если вы требуете спецификацию которая не расширяет спецификацию от которой -зависит объект, вы не получите ничего:: - - >>> registry.lookup(zope.interface.Interface, IP1, '') - -Между прочим, вы можете передать значение по умолчанию при запросе:: - - >>> registry.lookup(zope.interface.Interface, IP1, '', 42) - 42 - -Если вы пробуете получить интерфейс который объект не предоставляет вы также -не получите ничего:: - - >>> class IP3(IP2): - ... pass - >>> registry.lookup(IR1, IP3, '') - -Вы также не получите ничего если вы используете неверное имя:: - - >>> registry.lookup(IR1, IP1, 'bob') - >>> registry.register(IR1, IP2, 'bob', "Bob's 12") - >>> registry.lookup(IR1, IP1, 'bob') - "Bob's 12" - -Вы можете не использовать имя при запросе:: - - >>> registry.lookup(IR1, IP1) - 12 - -Если мы регистрируем объект который предоставляет IP1:: - - >>> registry.register(IR1, IP1, '', 11) - -тогда этот объект будет иметь преимущество перед O(12):: - - >>> registry.lookup(IR1, IP1, '') - 11 - -Также, если мы регистрируем объект для IR2 тогда он будет иметь преимущество -когда используется IR2:: - - >>> registry.register(IR2, IP1, '', 21) - >>> registry.lookup(IR2, IP1, '') - 21 - -Поиск того, что (если вообще что-то) зарегистрировано ------------------------------------------------------ - -Мы можем спросить есть-ли адаптер зарегистрированный для набора интерфейсов. -Это отличается от обычного запроса так как здесь мы ищем точное совпадение:: - - >>> print registry.registered(IR1, IP1) - 11 - - >>> print registry.registered(IR1, IP2) - 12 - - >>> print registry.registered(IR1, IP2, 'bob') - Bob's 12 - - - >>> print registry.registered(IR2, IP1) - 21 - - >>> print registry.registered(IR2, IP2) - None - -В последнем примере, None был возвращен потому, что для данного интерфейса -ничего не было зарегистрировано. - -lookup1 -------- - -Запрос одиночного адаптера - это наиболее частая операция и для нее есть -специализированная версия запроса которая получает на вход единственный -требуемый интерфейс:: - - >>> registry.lookup1(IR2, IP1, '') - 21 - >>> registry.lookup1(IR2, IP1) - 21 - -Адаптация на практике ---------------------- - -Реестр адаптеров предназначен для поддержки адаптации когда один объект -реализующий интерфейс адаптируется к другому объекту который поддерживает -другой интерфейс. Реестр адаптеров также поддерживает вычисление адаптеров. В -этом случае мы должны регистрировать фабрики для адаптеров:: - - >>> class IR(zope.interface.Interface): - ... pass - - >>> class X: - ... zope.interface.implements(IR) - - >>> class Y: - ... zope.interface.implements(IP1) - ... def __init__(self, context): - ... self.context = context - - >>> registry.register(IR, IP1, '', Y) - -В этом случае мы регистрируем класс как фабрику. Теперь мы можем вызвать -`queryAdapter` для получения адаптированного объекта:: - - >>> x = X() - >>> y = registry.queryAdapter(x, IP1) - >>> y.__class__.__name__ - 'Y' - >>> y.context is x - True - -Мы также можем регистрировать и запрашивать по имени:: - - >>> class Y2(Y): - ... pass - - >>> registry.register(IR, IP1, 'bob', Y2) - >>> y = registry.queryAdapter(x, IP1, 'bob') - >>> y.__class__.__name__ - 'Y2' - >>> y.context is x - True - -Когда фабрика для адаптера возвращает `None` - это рассматривается как если бы -адаптер не был найден. Это позволяет нам избежать адаптации (по желанию) и дает -возможность фабрике адаптера определить возможна ли адаптация основываясь на -состоянии объекта который адаптируется:: - - >>> def factory(context): - ... if context.name == 'object': - ... return 'adapter' - ... return None - - >>> class Object(object): - ... zope.interface.implements(IR) - ... name = 'object' - - >>> registry.register(IR, IP1, 'conditional', factory) - >>> obj = Object() - >>> registry.queryAdapter(obj, IP1, 'conditional') - 'adapter' - >>> obj.name = 'no object' - >>> registry.queryAdapter(obj, IP1, 'conditional') is None - True - >>> registry.queryAdapter(obj, IP1, 'conditional', 'default') - 'default' - -Альтернативный метод для предоставления такой же функциональности как и -`queryAdapter()` - это `adapter_hook()`:: - - >>> y = registry.adapter_hook(IP1, x) - >>> y.__class__.__name__ - 'Y' - >>> y.context is x - True - >>> y = registry.adapter_hook(IP1, x, 'bob') - >>> y.__class__.__name__ - 'Y2' - >>> y.context is x - True - -`adapter_hook()` просто меняет порядок аргументов для объекта и интерфейса. Это -используется для встраивания в механизм вызовов интерфейсов. - -Адаптеры по умолчанию ---------------------- - -Иногда вы можете захотеть предоставить адаптер который не будет ничего -адаптировать. Для этого нужно передать None как требуемый интерфейс:: - - >>> registry.register(None, IP1, '', 1) - -после этого вы можете использовать этот адаптер для интерфейсов для которых у -вас нет конкретного адаптера:: - - >>> class IQ(zope.interface.Interface): - ... pass - >>> registry.lookup(IQ, IP1, '') - 1 - -Конечно, конкретные адаптеры все еще используются когда необходимо:: - - >>> registry.lookup(IR2, IP1, '') - 21 - -Адаптеры классов ----------------- - -Вы можете регистрировать адаптеры для определений классов, что будет похоже на -регистрацию их для классов:: - - >>> registry.register(zope.interface.implementedBy(C2), IP1, '', 'C21') - >>> registry.lookup(zope.interface.implementedBy(C2), IP1, '') - 'C21' - -Адаптеры для словарей ---------------------- - -В какой-то момент было невозможно регистрировать адаптеры основанные на -словарях из-за ошибки. Давайте удостоверимся что это теперь работает:: - - >>> adapter = {} - >>> registry.register((), IQ, '', adapter) - >>> registry.lookup((), IQ, '') is adapter - True - -Удаление регистрации --------------------- - -Вы можете удалить регистрацию регистрируя None вместо объекта:: - - >>> registry.register(zope.interface.implementedBy(C2), IP1, '', None) - >>> registry.lookup(zope.interface.implementedBy(C2), IP1, '') - 21 - -Конечно это значит, что None не может быть зарегистрирован. Это исключение к -утверждению выше о том, что реестр не заботиться о том, что регистрируется. - -Мульти-адаптеры -=============== - -Вы можете адаптировать несколько спецификаций:: - - >>> registry.register(IR1, IQ, IP2, '', '1q2') - >>> registry.lookup(IR1, IQ, IP2, '') - '1q2' - >>> registry.lookup(IR2, IQ, IP1, '') - '1q2' - - >>> class IS(zope.interface.Interface): - ... pass - >>> registry.lookup(IR2, IS, IP1, '') - - >>> class IQ2(IQ): - ... pass - - >>> registry.lookup(IR2, IQ2, IP1, '') - '1q2' - - >>> registry.register(IR1, IQ2, IP2, '', '1q22') - >>> registry.lookup(IR2, IQ2, IP1, '') - '1q22' - -Мульти-адаптация ----------------- - -Вы можете адаптировать несколько объектов:: - - >>> class Q: - ... zope.interface.implements(IQ) - -Как и с одиночными адаптерами, мы регистрируем фабрику которая возвращает -класс:: - - >>> class IM(zope.interface.Interface): - ... pass - >>> class M: - ... zope.interface.implements(IM) - ... def __init__(self, x, q): - ... self.x, self.q = x, q - >>> registry.register(IR, IQ, IM, '', M) - -И затем мы можем вызвать `queryMultiAdapter` для вычисления адаптера:: - - >>> q = Q() - >>> m = registry.queryMultiAdapter((x, q), IM) - >>> m.__class__.__name__ - 'M' - >>> m.x is x and m.q is q - True - -и, конечно, мы можем использовать имена:: - - >>> class M2(M): - ... pass - >>> registry.register(IR, IQ, IM, 'bob', M2) - >>> m = registry.queryMultiAdapter((x, q), IM, 'bob') - >>> m.__class__.__name__ - 'M2' - >>> m.x is x and m.q is q - True - -Адаптеры по умолчанию ---------------------- - -Как и для одиночных адаптеров вы можете определить адаптер по умолчанию передав -None вместо *первой* спецификации:: - - >>> registry.register(None, IQ, IP2, '', 'q2') - >>> registry.lookup(IS, IQ, IP2, '') - 'q2' - -Нулевые адаптеры -================ - -Вы можете также адаптировать без спецификации:: - - >>> registry.register(, IP2, '', 2) - >>> registry.lookup(, IP2, '') - 2 - >>> registry.lookup(, IP1, '') - 2 - -Перечисление именованных адаптеров ----------------------------------- - -Адаптеры имеют имена. Иногда это полезно для получения всех именованных -адаптеров для заданного интерфейса:: - - >>> adapters = list(registry.lookupAll(IR1, IP1)) - >>> adapters.sort() - >>> assert adapters == (u'', 11), (u'bob', "Bob's 12") - -Это работает также и для мульти-адаптеров:: - - >>> registry.register(IR1, IQ2, IP2, 'bob', '1q2 for bob') - >>> adapters = list(registry.lookupAll(IR2, IQ2, IP1)) - >>> adapters.sort() - >>> assert adapters == (u'', '1q22'), (u'bob', '1q2 for bob') - -И даже для нулевых адаптеров:: - - >>> registry.register(, IP2, 'bob', 3) - >>> adapters = list(registry.lookupAll(, IP1)) - >>> adapters.sort() - >>> assert adapters == (u'', 2), (u'bob', 3) - -Подписки -======== - -Обычно мы хотим запросить объект который наиболее близко соответствует -спецификации. Иногда мы хотим получить все объекты которые соответствуют -какой-либо спецификации. Мы используем подписки для этого. Мы подписываем -объекты для спецификаций и затем позже находим все подписанные объекты:: - - >>> registry.subscribe(IR1, IP2, 'sub12 1') - >>> registry.subscriptions(IR1, IP2) - 'sub12 1' - -Заметьте, что в отличие от обычных адаптеров подписки не имеют имен. - -Вы можете иметь несколько подписчиков для одной спецификации:: - - >>> registry.subscribe(IR1, IP2, 'sub12 2') - >>> registry.subscriptions(IR1, IP2) - 'sub12 1', 'sub12 2' - -Если подписчики зарегистрированы для одних и тех же требуемых интерфейсов, они -возвращаются в порядке определения. - -Вы можете зарегистрировать подписчики для всех спецификаций используя None:: - - >>> registry.subscribe(None, IP1, 'sub_1') - >>> registry.subscriptions(IR2, IP1) - 'sub_1', 'sub12 1', 'sub12 2' - -Заметьте, что новый подписчик возвращается первым. Подписчики определенные -для менее общих требуемых интерфейсов возвращаются перед подписчиками -для более общих интерфейсов. - -Подписки могут смешиваться между несколькими совместимыми спецификациями:: - - >>> registry.subscriptions(IR2, IP1) - 'sub_1', 'sub12 1', 'sub12 2' - >>> registry.subscribe(IR1, IP1, 'sub11') - >>> registry.subscriptions(IR2, IP1) - 'sub_1', 'sub12 1', 'sub12 2', 'sub11' - >>> registry.subscribe(IR2, IP2, 'sub22') - >>> registry.subscriptions(IR2, IP1) - 'sub_1', 'sub12 1', 'sub12 2', 'sub11', 'sub22' - >>> registry.subscriptions(IR2, IP2) - 'sub12 1', 'sub12 2', 'sub22' - -Подписки могут существовать для нескольких спецификаций:: - - >>> registry.subscribe(IR1, IQ, IP2, 'sub1q2') - >>> registry.subscriptions(IR1, IQ, IP2) - 'sub1q2' - -Как и с одиночными подписчиками и адаптерами без подписок, вы можете определить -None для первого требуемого интерфейса, что бы задать значение по умолчанию:: - - >>> registry.subscribe(None, IQ, IP2, 'sub_q2') - >>> registry.subscriptions(IS, IQ, IP2) - 'sub_q2' - >>> registry.subscriptions(IR1, IQ, IP2) - 'sub_q2', 'sub1q2' - -Вы можете создать подписки которые независимы от любых спецификаций:: - - >>> list(registry.subscriptions(, IP1)) - - - >>> registry.subscribe(, IP2, 'sub2') - >>> registry.subscriptions(, IP1) - 'sub2' - >>> registry.subscribe(, IP1, 'sub1') - >>> registry.subscriptions(, IP1) - 'sub2', 'sub1' - >>> registry.subscriptions(, IP2) - 'sub2' - -Удаление регистрации подписчиков --------------------------------- - -Мы можем удалять регистрацию подписчиков. При удалении регистрации подписчика -мы можем удалить регистрацию заданного адаптера:: - - >>> registry.unsubscribe(IR1, IP1, 'sub11') - >>> registry.subscriptions(IR1, IP1) - 'sub_1', 'sub12 1', 'sub12 2' - -Если мы не задаем никакого значения тогда подписки будут удалены для всех -подписчиков совпадающих с заданным интерфейсом:: - - >>> registry.unsubscribe(IR1, IP2) - >>> registry.subscriptions(IR1, IP1) - 'sub_1' - -Адаптеры подписки ------------------ - -Обычно мы регистрируем фабрики для адаптеров которые затем позволяют нам -вычислять адаптеры, но с подписками мы получаем несколько адаптеров. Это пример -подписчика для нескольких объектов:: - - >>> registry.subscribe(IR, IQ, IM, M) - >>> registry.subscribe(IR, IQ, IM, M2) - - >>> subscribers = registry.subscribers((x, q), IM) - >>> len(subscribers) - 2 - >>> class_names = s.__class__.__name__ for s in subscribers - >>> class_names.sort() - >>> class_names - 'M', 'M2' - >>> (s.x is x and s.q is q) for s in subscribers - True, True - -подписчики фабрик адаптеров не могут возвращать None:: - - >>> def M3(x, y): - ... return None - - >>> registry.subscribe(IR, IQ, IM, M3) - >>> subscribers = registry.subscribers((x, q), IM) - >>> len(subscribers) - 2 - -Обработчики ------------ - -Обработчик - это подписанная фабрика которая не возвращает нормального -значения. Она возвращает None. Обработчик отличается от адаптеров тем, что он -делает всю работу когда вызывается фабрика. - -Для регистрации обработчика надо просто передать None как предоставляемый -интерфейс:: - - >>> def handler(event): - ... print 'handler', event - - >>> registry.subscribe(IR1, None, handler) - >>> registry.subscriptions(IR1, None) == handler - True
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/api
Deleted
-(directory)
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/api/adapters.rst.txt
Deleted
@@ -1,27 +0,0 @@ -================== - Adapter Registry -================== - -Usage of the adapter registry is documented in :ref:`adapter-registry`. - - -The adapter registry's API is defined by -:class:`zope.interface.interfaces.IAdapterRegistry`: - -.. autointerface:: zope.interface.interfaces.IAdapterRegistry - :members: - :member-order: bysource - - -The concrete implementations of ``IAdapterRegistry`` provided by this -package allows for some customization opportunities. - -.. autoclass:: zope.interface.adapter.BaseAdapterRegistry - :members: - :private-members: - -.. autoclass:: zope.interface.adapter.AdapterRegistry - :members: - -.. autoclass:: zope.interface.adapter.VerifyingAdapterRegistry - :members:
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/api/common.rst.txt
Deleted
@@ -1,50 +0,0 @@ -==================================== - Python Standard Library Interfaces -==================================== - -The ``zope.interface.common`` package provides interfaces for objects -distributed as part of the Python standard library. Importing these -modules (usually) has the effect of making the standard library objects -implement the correct interface. - -zope.interface.common.interface -=============================== - -.. automodule:: zope.interface.common.interfaces - -zope.interface.common.idatetime -=============================== - -.. automodule:: zope.interface.common.idatetime - -zope.interface.common.collections -================================= - -.. automodule:: zope.interface.common.collections - -zope.interface.common.numbers -============================= - -.. automodule:: zope.interface.common.numbers - -zope.interface.common.builtins -============================== - -.. automodule:: zope.interface.common.builtins - -zope.interface.common.io -======================== - -.. automodule:: zope.interface.common.io - -.. Deprecated or discouraged modules below this - -zope.interface.common.mapping -============================= - -.. automodule:: zope.interface.common.mapping - -zope.interface.common.sequence -============================== - -.. automodule:: zope.interface.common.sequence
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/api/components.rst.txt
Deleted
@@ -1,84 +0,0 @@ -====================== - Component Registries -====================== - -The component registry's API is defined by -``zope.interface.interfaces.IComponents``: - -.. autointerface:: zope.interface.interfaces.IComponentLookup - :members: - :member-order: bysource - - -.. autointerface:: zope.interface.interfaces.IComponentRegistry - :members: - :member-order: bysource - -.. autointerface:: zope.interface.interfaces.IComponents - :members: - :member-order: bysource - -One default implementation of `~zope.interface.interfaces.IComponents` is provided. - -.. autoclass:: zope.interface.registry.Components - -Events -====== - -Adding and removing components from the component registry create -registration and unregistration events. Like most things, they are -defined by an interface and a default implementation is provided. - -Registration ------------- - -.. autointerface:: zope.interface.interfaces.IObjectEvent -.. autointerface:: zope.interface.interfaces.IRegistrationEvent - -.. autointerface:: zope.interface.interfaces.IRegistered -.. autoclass:: zope.interface.interfaces.Registered - -.. autointerface:: zope.interface.interfaces.IUnregistered -.. autoclass:: zope.interface.interfaces.Unregistered - - -Details -------- - -These are all types of ``IObjectEvent``, meaning they have an object -that provides specific details about the event. Component registries -create detail objects for four types of components they manage. - -All four share a common base interface. - -.. autointerface:: zope.interface.interfaces.IRegistration - -* Utilities - - .. autointerface:: zope.interface.interfaces.IUtilityRegistration - .. autoclass:: zope.interface.registry.UtilityRegistration - -* Handlers - - .. autointerface:: zope.interface.interfaces.IHandlerRegistration - .. autoclass:: zope.interface.registry.HandlerRegistration - -* Adapters - - For ease of implementation, a shared base class is used for these - events. It should not be referenced by clients, but it is documented - to show the common attributes. - - .. autointerface:: zope.interface.interfaces._IBaseAdapterRegistration - - .. autointerface:: zope.interface.interfaces.IAdapterRegistration - .. autoclass:: zope.interface.registry.AdapterRegistration - - .. autointerface:: zope.interface.interfaces.ISubscriptionAdapterRegistration - .. autoclass:: zope.interface.registry.SubscriptionRegistration - -Exceptions -========== - -.. autoclass:: zope.interface.interfaces.ComponentLookupError -.. autoclass:: zope.interface.interfaces.Invalid
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/api/declarations.rst.txt
Deleted
@@ -1,975 +0,0 @@ -================================================== - Declaring and Checking The Interfaces of Objects -================================================== - -Declaring what interfaces an object implements or provides, and later -being able to check those, is an important part of this package. -Declaring interfaces, in particular, can be done both statically at -object definition time and dynamically later on. - -The functionality that allows declaring and checking interfaces is -provided directly in the ``zope.interface`` module. It is described by -the interface ``zope.interface.interfaces.IInterfaceDeclaration``. We -will first look at that interface, and then we will look more -carefully at each object it documents, including providing examples. - -.. autointerface:: zope.interface.interfaces.IInterfaceDeclaration - - -.. currentmodule:: zope.interface - -Declaring Interfaces -==================== - -To declare an interface itself, extend the ``Interface`` base class. - -.. autointerface:: Interface - :noindex: - -.. autofunction:: taggedValue - :noindex: - - .. documented more thoroughly in README.rst - -.. autofunction:: invariant - :noindex: - - .. documented in README.rst - -.. autofunction:: interfacemethod - -Declaring The Interfaces of Objects -=================================== - - -implementer ------------ - -.. autoclass:: implementer - - -implementer_only ----------------- - -.. autoclass:: implementer_only - - -classImplementsOnly -------------------- - -.. autofunction:: classImplementsOnly - - -Consider the following example: - -.. doctest:: - - >>> from zope.interface import implementedBy - >>> from zope.interface import implementer - >>> from zope.interface import classImplementsOnly - >>> from zope.interface import Interface - >>> class I1(Interface): pass - ... - >>> class I2(Interface): pass - ... - >>> class I3(Interface): pass - ... - >>> class I4(Interface): pass - ... - >>> @implementer(I3) - ... class A(object): - ... pass - >>> @implementer(I4) - ... class B(object): - ... pass - >>> class C(A, B): - ... pass - >>> classImplementsOnly(C, I1, I2) - >>> i.getName() for i in implementedBy(C) - 'I1', 'I2' - -Instances of ``C`` provide only ``I1``, ``I2``, and regardless of -whatever interfaces instances of ``A`` and ``B`` implement. - - -classImplements ---------------- - -.. autofunction:: classImplements - -Consider the following example: - -.. doctest:: - - >>> from zope.interface import Interface - >>> from zope.interface import classImplements - >>> from zope.interface.ro import is_consistent - >>> class I1(Interface): pass - ... - >>> class I2(Interface): pass - ... - >>> class IA(Interface): pass - ... - >>> class IB(Interface): pass - ... - >>> class I5(Interface): pass - ... - >>> @implementer(IA) - ... class A(object): - ... pass - >>> @implementer(IB) - ... class B(object): - ... pass - >>> class C(A, B): - ... pass - >>> classImplements(C, I1, I2) - >>> i.getName() for i in implementedBy(C) - 'I1', 'I2', 'IA', 'IB' - -Instances of ``C`` provide ``I1`` and ``I2``, plus whatever -instances of ``A`` and ``B`` provide. - -.. doctest:: - - >>> classImplements(C, I5) - >>> i.getName() for i in implementedBy(C) - 'I1', 'I2', 'I5', 'IA', 'IB' - -Instances of ``C`` now also provide ``I5``. Notice how ``I5`` was -added to the *end* of the list of things provided directly by ``C``. - -If we ask a class to implement an interface that extends -an interface it already implements, that interface will go at the -*beginning* of the list, in order to preserve a consistent resolution -order. - -.. doctest:: - - >>> class I6(I5): pass - >>> class I7(IA): pass - >>> classImplements(C, I6, I7) - >>> i.getName() for i in implementedBy(C) - 'I6', 'I1', 'I2', 'I5', 'I7', 'IA', 'IB' - >>> is_consistent(implementedBy(C)) - True - -This cannot be used to introduce duplicates. - -.. doctest:: - - >>> classImplements(C, IA, IB, I1, I2) - >>> i.getName() for i in implementedBy(C) - 'I6', 'I1', 'I2', 'I5', 'I7', 'IA', 'IB' - - -classImplementsFirst --------------------- - -.. autofunction:: classImplementsFirst - -Consider the following example: - -.. doctest:: - - >>> from zope.interface import Interface - >>> from zope.interface import classImplements - >>> from zope.interface import classImplementsFirst - >>> class I1(Interface): pass - ... - >>> class I2(Interface): pass - ... - >>> class IA(Interface): pass - ... - >>> class IB(Interface): pass - ... - >>> class I5(Interface): pass - ... - >>> @implementer(IA) - ... class A(object): - ... pass - >>> @implementer(IB) - ... class B(object): - ... pass - >>> class C(A, B): - ... pass - >>> classImplementsFirst(C, I2) - >>> classImplementsFirst(C, I1) - >>> i.getName() for i in implementedBy(C) - 'I1', 'I2', 'IA', 'IB' - -Instances of ``C`` provide ``I1``, ``I2``, ``I5``, and whatever -interfaces instances of ``A`` and ``B`` provide. - -.. doctest:: - - >>> classImplementsFirst(C, I5) - >>> i.getName() for i in implementedBy(C) - 'I5', 'I1', 'I2', 'IA', 'IB' - -Instances of ``C`` now also provide ``I5``. Notice how ``I5`` was -added to the *beginning* of the list of things provided directly by -``C``. Unlike `classImplements`, this ignores interface inheritance -and does not attempt to ensure a consistent resolution order (except -that it continues to elide interfaces already implemented through -class inheritance):: - -.. doctest:: - - >>> class IBA(IB, IA): - ... pass - >>> classImplementsFirst(C, IBA) - >>> classImplementsFirst(C, IA) - >>> i.getName() for i in implementedBy(C) - 'IBA', 'I5', 'I1', 'I2', 'IA', 'IB' - -This cannot be used to introduce duplicates. - -.. doctest:: - - >>> len(implementedBy(C).declared) - 4 - >>> classImplementsFirst(C, IA) - >>> classImplementsFirst(C, IBA) - >>> classImplementsFirst(C, IA) - >>> classImplementsFirst(C, IBA) - >>> i.getName() for i in implementedBy(C) - 'IBA', 'I5', 'I1', 'I2', 'IA', 'IB' - >>> len(implementedBy(C).declared) - 4 - - -directlyProvides ----------------- - -.. autofunction:: directlyProvides - - -Consider the following example: - -.. doctest:: - - >>> from zope.interface import Interface - >>> from zope.interface import providedBy - >>> from zope.interface import directlyProvides - >>> class I1(Interface): pass - ... - >>> class I2(Interface): pass - ... - >>> class IA1(Interface): pass - ... - >>> class IA2(Interface): pass - ... - >>> class IB(Interface): pass - ... - >>> class IC(Interface): pass - ... - >>> @implementer(IA1, IA2) - ... class A(object): - ... pass - >>> @implementer(IB) - ... class B(object): - ... pass - >>> @implementer(IC) - ... class C(A, B): - ... pass - >>> ob = C() - >>> directlyProvides(ob, I1, I2) - >>> int(I1 in providedBy(ob)) - 1 - >>> int(I2 in providedBy(ob)) - 1 - >>> int(IA1 in providedBy(ob)) - 1 - >>> int(IA2 in providedBy(ob)) - 1 - >>> int(IB in providedBy(ob)) - 1 - >>> int(IC in providedBy(ob)) - 1 - -The object, ``ob`` provides ``I1``, ``I2``, and whatever interfaces -instances have been declared for instances of ``C``. - -To remove directly provided interfaces, use ``directlyProvidedBy`` and -subtract the unwanted interfaces. For example: - -.. doctest:: - - >>> from zope.interface import directlyProvidedBy - >>> directlyProvides(ob, directlyProvidedBy(ob)-I2) - >>> int(I1 in providedBy(ob)) - 1 - >>> int(I2 in providedBy(ob)) - 0 - -removes ``I2`` from the interfaces directly provided by ``ob``. The object, -``ob`` no longer directly provides ``I2``, although it might still -provide ``I2`` if its class implements ``I2``. - -To add directly provided interfaces, use ``directlyProvidedBy`` and -include additional interfaces. For example: - -.. doctest:: - - >>> int(I2 in providedBy(ob)) - 0 - >>> from zope.interface import directlyProvidedBy - >>> directlyProvides(ob, directlyProvidedBy(ob), I2) - -adds ``I2`` to the interfaces directly provided by ``ob``: - -.. doctest:: - - >>> int(I2 in providedBy(ob)) - 1 - -We need to avoid setting this attribute on meta classes that -don't support descriptors. - -We can do away with this check when we get rid of the old EC - - -alsoProvides ------------- - -.. autofunction:: alsoProvides - - -Consider the following example: - -.. doctest:: - - >>> from zope.interface import Interface - >>> from zope.interface import alsoProvides - >>> class I1(Interface): pass - ... - >>> class I2(Interface): pass - ... - >>> class IA1(Interface): pass - ... - >>> class IA2(Interface): pass - ... - >>> class IB(Interface): pass - ... - >>> class IC(Interface): pass - ... - >>> @implementer(IA1, IA2) - ... class A(object): - ... pass - >>> @implementer(IB) - ... class B(object): - ... pass - >>> @implementer(IC) - ... class C(A, B): - ... pass - >>> ob = C() - >>> directlyProvides(ob, I1) - >>> int(I1 in providedBy(ob)) - 1 - >>> int(I2 in providedBy(ob)) - 0 - >>> int(IA1 in providedBy(ob)) - 1 - >>> int(IA2 in providedBy(ob)) - 1 - >>> int(IB in providedBy(ob)) - 1 - >>> int(IC in providedBy(ob)) - 1 - >>> alsoProvides(ob, I2) - >>> int(I1 in providedBy(ob)) - 1 - >>> int(I2 in providedBy(ob)) - 1 - >>> int(IA1 in providedBy(ob)) - 1 - >>> int(IA2 in providedBy(ob)) - 1 - >>> int(IB in providedBy(ob)) - 1 - >>> int(IC in providedBy(ob)) - 1 - -The object, ``ob`` provides ``I1``, ``I2``, and whatever interfaces -instances have been declared for instances of ``C``. Notice that the -``alsoProvides`` just extends the provided interfaces. - - -noLongerProvides ----------------- - -.. autofunction:: noLongerProvides - -Consider the following two interfaces: - -.. doctest:: - - >>> from zope.interface import Interface - >>> class I1(Interface): pass - ... - >>> class I2(Interface): pass - ... - -``I1`` is provided through the class, ``I2`` is directly provided -by the object: - -.. doctest:: - - >>> @implementer(I1) - ... class C(object): - ... pass - >>> c = C() - >>> alsoProvides(c, I2) - >>> I2.providedBy(c) - True - -Remove ``I2`` from ``c`` again: - -.. doctest:: - - >>> from zope.interface import noLongerProvides - >>> noLongerProvides(c, I2) - >>> I2.providedBy(c) - False - -Removing an interface that is provided through the class is not possible: - -.. doctest:: - - >>> noLongerProvides(c, I1) - Traceback (most recent call last): - ... - ValueError: Can only remove directly provided interfaces. - - -provider --------- - -.. autoclass:: provider - -For example: - -.. doctest:: - - >>> from zope.interface import Interface - >>> from zope.interface import implementer - >>> from zope.interface import provider - >>> class IFooFactory(Interface): - ... pass - >>> class IFoo(Interface): - ... pass - >>> @implementer(IFoo) - ... @provider(IFooFactory) - ... class C(object): - ... pass - >>> i.getName() for i in C.__provides__ - 'IFooFactory' - >>> i.getName() for i in C().__provides__ - 'IFoo' - -Which is equivalent to: - -.. doctest:: - - >>> from zope.interface import Interface - >>> class IFoo(Interface): pass - ... - >>> class IFooFactory(Interface): pass - ... - >>> @implementer(IFoo) - ... class C(object): - ... pass - >>> directlyProvides(C, IFooFactory) - >>> i.getName() for i in C.__providedBy__ - 'IFooFactory' - >>> i.getName() for i in C().__providedBy__ - 'IFoo' - - -moduleProvides --------------- - -.. autofunction:: moduleProvides - - -named ------ - -.. autoclass:: zope.interface.declarations.named - -For example: - -.. doctest:: - - >>> from zope.interface.declarations import named - - >>> @named('foo') - ... class Foo(object): - ... pass - - >>> Foo.__component_name__ - 'foo' - -When registering an adapter or utility component, the registry looks for the -``__component_name__`` attribute and uses it, if no name was explicitly -provided. - - -Deprecated Functions --------------------- - -implements -~~~~~~~~~~ - -.. caution:: Does not work on Python 3. Use the `implementer` decorator instead. - -.. autofunction:: implements - - -implementsOnly -~~~~~~~~~~~~~~ - -.. caution:: Does not work on Python 3. Use the `implementer_only` decorator instead. - -.. autofunction:: implementsOnly - - -classProvides -~~~~~~~~~~~~~ - -.. caution:: Does not work on Python 3. Use the `provider` decorator instead. - -.. autofunction:: classProvides - - -Querying The Interfaces Of Objects -================================== - -All of these functions return an -`~zope.interface.interfaces.IDeclaration`. -You'll notice that an ``IDeclaration`` is a type of -`~zope.interface.interfaces.ISpecification`, as is -``zope.interface.Interface``, so they share some common behaviour. - -.. autointerface:: zope.interface.interfaces.IDeclaration - :members: - :member-order: bysource - - -implementedBy -------------- - -.. autofunction:: implementedBy - - -Consider the following example: - -.. doctest:: - - >>> from zope.interface import Interface - >>> from zope.interface import implementer - >>> from zope.interface import classImplementsOnly - >>> from zope.interface import implementedBy - >>> class I1(Interface): pass - ... - >>> class I2(Interface): pass - ... - >>> class I3(Interface): pass - ... - >>> class I4(Interface): pass - ... - >>> @implementer(I3) - ... class A(object): - ... pass - >>> @implementer(I4) - ... class B(object): - ... pass - >>> class C(A, B): - ... pass - >>> classImplementsOnly(C, I1, I2) - >>> i.getName() for i in implementedBy(C) - 'I1', 'I2' - -Instances of ``C`` provide only ``I1``, ``I2``, and regardless of -whatever interfaces instances of ``A`` and ``B`` implement. - -Another example: - -.. doctest:: - - >>> from zope.interface import Interface - >>> class I1(Interface): pass - ... - >>> class I2(I1): pass - ... - >>> class I3(Interface): pass - ... - >>> class I4(I3): pass - ... - >>> @implementer(I2) - ... class C1(object): - ... pass - >>> @implementer(I3) - ... class C2(C1): - ... pass - >>> i.getName() for i in implementedBy(C2) - 'I3', 'I2' - -Really, any object should be able to receive a successful answer, even -an instance: - -.. doctest:: - - >>> class Callable(object): - ... def __call__(self): - ... return self - >>> implementedBy(Callable()) - classImplements(builtins.?) - -Note that the name of the spec ends with a '?', because the ``Callable`` -instance does not have a ``__name__`` attribute. - -This also manages storage of implementation specifications. - - -providedBy ----------- - -.. autofunction:: providedBy - - -directlyProvidedBy ------------------- - -.. autofunction:: directlyProvidedBy - - -Classes -======= - - -Declarations ------------- - -Declaration objects implement the API defined by -:class:`~zope.interface.interfaces.IDeclaration`. - - -.. autoclass:: Declaration - - -Exmples for :meth:`Declaration.__contains__`: - -.. doctest:: - - >>> from zope.interface.declarations import Declaration - >>> from zope.interface import Interface - >>> class I1(Interface): pass - ... - >>> class I2(I1): pass - ... - >>> class I3(Interface): pass - ... - >>> class I4(I3): pass - ... - >>> spec = Declaration(I2, I3) - >>> spec = Declaration(I4, spec) - >>> int(I1 in spec) - 0 - >>> int(I2 in spec) - 1 - >>> int(I3 in spec) - 1 - >>> int(I4 in spec) - 1 - -Exmples for :meth:`Declaration.__iter__`: - -.. doctest:: - - >>> from zope.interface import Interface - >>> class I1(Interface): pass - ... - >>> class I2(I1): pass - ... - >>> class I3(Interface): pass - ... - >>> class I4(I3): pass - ... - >>> spec = Declaration(I2, I3) - >>> spec = Declaration(I4, spec) - >>> i = iter(spec) - >>> x.getName() for x in i - 'I4', 'I2', 'I3' - >>> list(i) - - -Exmples for :meth:`Declaration.flattened`: - -.. doctest:: - - >>> from zope.interface import Interface - >>> class I1(Interface): pass - ... - >>> class I2(I1): pass - ... - >>> class I3(Interface): pass - ... - >>> class I4(I3): pass - ... - >>> spec = Declaration(I2, I3) - >>> spec = Declaration(I4, spec) - >>> i = spec.flattened() - >>> x.getName() for x in i - 'I4', 'I2', 'I3', 'I1', 'Interface' - >>> list(i) - - -Exmples for :meth:`Declaration.__sub__`: - -.. doctest:: - - >>> from zope.interface import Interface - >>> class I1(Interface): pass - ... - >>> class I2(I1): pass - ... - >>> class I3(Interface): pass - ... - >>> class I4(I3): pass - ... - >>> spec = Declaration() - >>> iface.getName() for iface in spec - - >>> spec -= I1 - >>> iface.getName() for iface in spec - - >>> spec -= Declaration(I2) - >>> iface.getName() for iface in spec - - >>> spec = Declaration(I2, I4) - >>> iface.getName() for iface in spec - 'I2', 'I4' - >>> iface.getName() for iface in spec - I4 - 'I2' - >>> iface.getName() for iface in spec - I1 - 'I4' - >>> iface.getName() for iface - ... in spec - Declaration(I4) - 'I2' - -Exmples for :meth:`Declaration.__add__`: - -.. doctest:: - - >>> from zope.interface import Interface - >>> class IRoot1(Interface): pass - ... - >>> class IDerived1(IRoot1): pass - ... - >>> class IRoot2(Interface): pass - ... - >>> class IDerived2(IRoot2): pass - ... - >>> spec = Declaration() - >>> iface.getName() for iface in spec - - >>> iface.getName() for iface in spec+IRoot1 - 'IRoot1' - >>> iface.getName() for iface in IRoot1+spec - 'IRoot1' - >>> spec2 = spec - >>> spec += IRoot1 - >>> iface.getName() for iface in spec - 'IRoot1' - >>> iface.getName() for iface in spec2 - - >>> spec2 += Declaration(IDerived2, IRoot2) - >>> iface.getName() for iface in spec2 - 'IDerived2', 'IRoot2' - >>> iface.getName() for iface in spec+spec2 - 'IRoot1', 'IDerived2', 'IRoot2' - >>> iface.getName() for iface in spec2+spec - 'IDerived2', 'IRoot2', 'IRoot1' - >>> iface.getName() for iface in (spec+spec2).__bases__ - 'IRoot1', 'IDerived2', 'IRoot2' - >>> iface.getName() for iface in (spec2+spec).__bases__ - 'IDerived2', 'IRoot2', 'IRoot1' - - - -ProvidesClass -------------- - -.. autoclass:: zope.interface.declarations.ProvidesClass - - -Descriptor semantics (via ``Provides.__get__``): - -.. doctest:: - - >>> from zope.interface import Interface - >>> class IFooFactory(Interface): - ... pass - >>> class C(object): - ... pass - >>> from zope.interface.declarations import ProvidesClass - >>> C.__provides__ = ProvidesClass(C, IFooFactory) - >>> i.getName() for i in C.__provides__ - 'IFooFactory' - >>> getattr(C(), '__provides__', 0) - 0 - - -Implementation Details -====================== - -The following section discusses some implementation details and -demonstrates their use. You'll notice that they are all demonstrated -using the previously-defined functions. - -Provides --------- - -.. autofunction:: Provides - -In the examples below, we are going to make assertions about -the size of the weakvalue dictionary. For the assertions to be -meaningful, we need to force garbage collection to make sure garbage -objects are, indeed, removed from the system. Depending on how Python -is run, we may need to make multiple calls to be sure. We provide a -collect function to help with this: - -.. doctest:: - - >>> import gc - >>> def collect(): - ... for i in range(4): - ... gc.collect() - >>> collect() - >>> from zope.interface import directlyProvides - >>> from zope.interface.declarations import InstanceDeclarations - >>> before = len(InstanceDeclarations) - >>> class C(object): - ... pass - >>> from zope.interface import Interface - >>> class I(Interface): - ... pass - >>> c1 = C() - >>> c2 = C() - >>> len(InstanceDeclarations) == before - True - >>> directlyProvides(c1, I) - >>> len(InstanceDeclarations) == before + 1 - True - >>> directlyProvides(c2, I) - >>> len(InstanceDeclarations) == before + 1 - True - >>> del c1 - >>> collect() - >>> len(InstanceDeclarations) == before + 1 - True - >>> del c2 - >>> collect() - >>> len(InstanceDeclarations) == before - True - - -ObjectSpecification -------------------- - -.. autofunction:: zope.interface.declarations.ObjectSpecification - - -For example: - -.. doctest:: - - >>> from zope.interface import Interface - >>> from zope.interface import implementer_only - >>> class I1(Interface): pass - ... - >>> class I2(Interface): pass - ... - >>> class I3(Interface): pass - ... - >>> class I31(I3): pass - ... - >>> class I4(Interface): pass - ... - >>> class I5(Interface): pass - ... - >>> @implementer(I1) - ... class A(object): - ... pass - >>> class B(object): - ... __implemented__ = I2 - >>> @implementer(I31) - ... class C(A, B): - ... pass - >>> c = C() - >>> directlyProvides(c, I4) - >>> i.getName() for i in providedBy(c) - 'I4', 'I31', 'I1', 'I2' - >>> i.getName() for i in providedBy(c).flattened() - 'I4', 'I31', 'I3', 'I1', 'I2', 'Interface' - >>> int(I1 in providedBy(c)) - 1 - >>> int(I3 in providedBy(c)) - 0 - >>> int(providedBy(c).extends(I3)) - 1 - >>> int(providedBy(c).extends(I31)) - 1 - >>> int(providedBy(c).extends(I5)) - 0 - >>> @implementer_only(I31) - ... class COnly(A, B): - ... pass - >>> @implementer(I5) - ... class D(COnly): - ... pass - >>> c = D() - >>> directlyProvides(c, I4) - >>> i.getName() for i in providedBy(c) - 'I4', 'I5', 'I31' - >>> i.getName() for i in providedBy(c).flattened() - 'I4', 'I5', 'I31', 'I3', 'Interface' - >>> int(I1 in providedBy(c)) - 0 - >>> int(I3 in providedBy(c)) - 0 - >>> int(providedBy(c).extends(I3)) - 1 - >>> int(providedBy(c).extends(I1)) - 0 - >>> int(providedBy(c).extends(I31)) - 1 - >>> int(providedBy(c).extends(I5)) - 1 - -ObjectSpecificationDescriptor ------------------------------ - -.. autoclass:: zope.interface.declarations.ObjectSpecificationDescriptor - -For example: - -.. doctest:: - - >>> from zope.interface import Interface - >>> class IFoo(Interface): pass - ... - >>> class IFooFactory(Interface): pass - ... - >>> @implementer(IFoo) - ... @provider(IFooFactory) - ... class C(object): - ... pass - >>> i.getName() for i in C.__providedBy__ - 'IFooFactory' - >>> i.getName() for i in C().__providedBy__ - 'IFoo' - -Get an ObjectSpecification bound to either an instance or a class, -depending on how we were accessed.
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/api/index.rst.txt
Deleted
@@ -1,15 +0,0 @@ -=============== - API Reference -=============== - -Contents: - -.. toctree:: - :maxdepth: 2 - - specifications - declarations - adapters - components - common - ro
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/api/ro.rst.txt
Deleted
@@ -1,19 +0,0 @@ -=========================================== - Computing The Resolution Order (Priority) -=========================================== - -Just as Python classes have a method resolution order that determines -which implementation of a method gets used when inheritance is used, -interfaces have a resolution order that determines their ordering when -searching for adapters. - -That order is computed by ``zope.interface.ro.ro``. This is an -internal module not generally needed by a user of ``zope.interface``, -but its documentation can be helpful to understand how orders are -computed. - -``zope.interface.ro`` -===================== - -.. automodule:: zope.interface.ro - :member-order: alphabetical
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/api/specifications.rst.txt
Deleted
@@ -1,380 +0,0 @@ -========================== - Interface Specifications -========================== - -.. currentmodule:: zope.interface.interfaces - - -This document discusses the actual interface objects themselves. We -begin with a basic concept of specifying an object's behaviour (with -an `ISpecification`), and then we describe the way we write such a -specification (`IInterface`). Combinations of specifications (e.g., an -object that provides multiple interfaces) are covered by -`IDeclaration`. - -Specification -============= - -Specification objects implement the API defined by -:class:`ISpecification`: - -.. autointerface:: ISpecification - :members: - :member-order: bysource - -.. autoclass:: zope.interface.interface.Specification - :no-members: - -For example: - -.. doctest:: - - >>> from zope.interface.interface import Specification - >>> from zope.interface import Interface - >>> class I1(Interface): - ... pass - >>> class I2(I1): - ... pass - >>> class I3(I2): - ... pass - >>> i.__name__ for i in I1.__bases__ - 'Interface' - >>> i.__name__ for i in I2.__bases__ - 'I1' - >>> I3.extends(I1) - True - >>> I2.__bases__ = (Interface, ) - >>> i.__name__ for i in I2.__bases__ - 'Interface' - >>> I3.extends(I1) - False - -Exmples for :meth:`.Specification.providedBy`: - -.. doctest:: - - >>> from zope.interface import * - >>> class I1(Interface): - ... pass - >>> @implementer(I1) - ... class C(object): - ... pass - >>> c = C() - >>> class X(object): - ... pass - >>> x = X() - >>> I1.providedBy(x) - False - >>> I1.providedBy(C) - False - >>> I1.providedBy(c) - True - >>> directlyProvides(x, I1) - >>> I1.providedBy(x) - True - >>> directlyProvides(C, I1) - >>> I1.providedBy(C) - True - -Examples for :meth:`.Specification.isOrExtends`: - -.. doctest:: - - >>> from zope.interface import Interface - >>> from zope.interface.declarations import Declaration - >>> class I1(Interface): pass - ... - >>> class I2(I1): pass - ... - >>> class I3(Interface): pass - ... - >>> class I4(I3): pass - ... - >>> spec = Declaration() - >>> int(spec.extends(Interface)) - 1 - >>> spec = Declaration(I2) - >>> int(spec.extends(Interface)) - 1 - >>> int(spec.extends(I1)) - 1 - >>> int(spec.extends(I2)) - 1 - >>> int(spec.extends(I3)) - 0 - >>> int(spec.extends(I4)) - 0 - -Examples for :meth:`.Specification.interfaces`: - -.. doctest:: - - >>> from zope.interface import Interface - >>> class I1(Interface): pass - ... - >>> class I2(I1): pass - ... - >>> class I3(Interface): pass - ... - >>> class I4(I3): pass - ... - >>> spec = Specification((I2, I3)) - >>> spec = Specification((I4, spec)) - >>> i = spec.interfaces() - >>> x.getName() for x in i - 'I4', 'I2', 'I3' - >>> list(i) - - -Exmples for :meth:`.Specification.extends`: - -.. doctest:: - - >>> from zope.interface import Interface - >>> from zope.interface.declarations import Declaration - >>> class I1(Interface): pass - ... - >>> class I2(I1): pass - ... - >>> class I3(Interface): pass - ... - >>> class I4(I3): pass - ... - >>> spec = Declaration() - >>> int(spec.extends(Interface)) - 1 - >>> spec = Declaration(I2) - >>> int(spec.extends(Interface)) - 1 - >>> int(spec.extends(I1)) - 1 - >>> int(spec.extends(I2)) - 1 - >>> int(spec.extends(I3)) - 0 - >>> int(spec.extends(I4)) - 0 - >>> I2.extends(I2) - False - >>> I2.extends(I2, False) - True - >>> I2.extends(I2, strict=False) - True - -.. _spec_eq_hash: - -Equality, Hashing, and Comparisons ----------------------------------- - -Specifications (including their notable subclass `Interface`), are -hashed and compared (sorted) based solely on their ``__name__`` and -``__module__``, not including any information about their enclosing -scope, if any (e.g., their ``__qualname__``). This means that any two -objects created with the same name and module are considered equal and -map to the same value in a dictionary. - -.. doctest:: - - >>> from zope.interface import Interface - >>> class I1(Interface): pass - >>> orig_I1 = I1 - >>> class I1(Interface): pass - >>> I1 is orig_I1 - False - >>> I1 == orig_I1 - True - >>> d = {I1: 42} - >>> dorig_I1 - 42 - >>> def make_nested(): - ... class I1(Interface): pass - ... return I1 - >>> nested_I1 = make_nested() - >>> I1 == orig_I1 == nested_I1 - True - -Caveats -~~~~~~~ - -While this behaviour works well with :ref:`pickling (persistence) -<global_persistence>`, it has some potential downsides to be aware of. - -.. rubric:: Weak References - -The first downside involves weak references. Because weak references -hash the same as their underlying object, this can lead to surprising -results when weak references are involved, especially if there are -cycles involved or if the garbage collector is not based on reference -counting (e.g., PyPy). For example, if you redefine an interface named -the same as an interface being used in a ``WeakKeyDictionary``, you -can get a ``KeyError``, even if you put the new interface into the -dictionary. - - -.. doctest:: - - >>> from zope.interface import Interface - >>> import gc - >>> from weakref import WeakKeyDictionary - >>> wr_dict = WeakKeyDictionary() - >>> class I1(Interface): pass - >>> wr_dictI1 = 42 - >>> orig_I1 = I1 # Make sure it stays alive - >>> class I1(Interface): pass - >>> wr_dictI1 = 2020 - >>> del orig_I1 - >>> _ = gc.collect() # Sometime later, gc runs and makes sure the original is gone - >>> wr_dictI1 # Cleaning up the original weakref removed the new one - Traceback (most recent call last): - ... - KeyError: ... - -This is mostly likely a problem in test cases where it is tempting to -use the same named interfaces in different test methods. If references -to them escape, especially if they are used as the bases of other -interfaces, you may find surprising ``KeyError`` exceptions. For this -reason, it is best to use distinct names for local interfaces within -the same test module. - -.. rubric:: Providing Dynamic Interfaces - -If you return an interface created inside a function or method, or -otherwise let it escape outside the bounds of that function (such as -by having an object provide it), it's important to be aware that it -will compare and hash equal to *any* other interface defined in that -same module with the same name. This includes interface objects -created by other invocations of that function. - -This can lead to surprising results when querying against those -interfaces. We can demonstrate by creating a module-level interface -with a common name, and checking that it is provided by an object: - -.. doctest:: - - >>> from zope.interface import Interface, alsoProvides, providedBy - >>> class ICommon(Interface): - ... pass - >>> class Obj(object): - ... pass - >>> obj = Obj() - >>> alsoProvides(obj, ICommon) - >>> len(list(providedBy(obj))) - 1 - >>> ICommon.providedBy(obj) - True - -Next, in the same module, we will define a function that dynamically -creates an interface of the same name and adds it to an object. - -.. doctest:: - - >>> def add_interfaces(obj): - ... class ICommon(Interface): - ... pass - ... class I2(Interface): - ... pass - ... alsoProvides(obj, ICommon, I2) - ... return ICommon - ... - >>> dynamic_ICommon = add_interfaces(obj) - -The two instances are *not* identical, but they are equal, and *obj* -provides them both: - -.. doctest:: - - >>> ICommon is dynamic_ICommon - False - >>> ICommon == dynamic_ICommon - True - >>> ICommon.providedBy(obj) - True - >>> dynamic_ICommon.providedBy(obj) - True - -At this point, we've effectively called ``alsoProvides(obj, ICommon, -dynamic_ICommon, I2)``, where the last two interfaces were locally -defined in the function. So checking how many interfaces *obj* now -provides should return three, right? - -.. doctest:: - - >>> len(list(providedBy(obj))) - 2 - -Because ``ICommon == dynamic_ICommon`` due to having the same -``__name__`` and ``__module__``, only one of them is actually provided -by the object, for a total of two provided interfaces. (Exactly which -one is undefined.) Likewise, if we run the same function again, *obj* -will still only provide two interfaces - -.. doctest:: - - >>> _ = add_interfaces(obj) - >>> len(list(providedBy(obj))) - 2 - - -Interface -========= - -Interfaces are a particular type of `ISpecification` and implement the -API defined by :class:`IInterface`. - -Before we get there, we need to discuss two related concepts. The -first is that of an "element", which provides us a simple way to query -for information generically (this is important because we'll see that -``IInterface`` implements this interface): - -.. - IElement defines __doc__ to be an Attribute, so the docstring - in the class isn't used._ - -.. autointerface:: IElement - - Objects that have basic documentation and tagged values. - - Known derivatives include :class:`IAttribute` and its derivative - :class:`IMethod`; these have no notion of inheritance. - :class:`IInterface` is also a derivative, and it does have a - notion of inheritance, expressed through its ``__bases__`` and - ordered in its ``__iro__`` (both defined by - :class:`ISpecification`). - - -.. autoclass:: zope.interface.interface.Element - :no-members: - -Next, we look at ``IAttribute`` and ``IMethod``. These make up the -content, or body, of an ``Interface``. - -.. autointerface:: zope.interface.interfaces.IAttribute -.. autoclass:: zope.interface.interface.Attribute - :no-members: - -.. autointerface:: IMethod -.. autoclass:: zope.interface.interface.Method - :no-members: - -Finally we can look at the definition of ``IInterface``. - -.. autointerface:: IInterface - -.. autointerface:: zope.interface.Interface - -Usage ------ - -Exmples for :meth:`InterfaceClass.extends`: - -.. doctest:: - - >>> from zope.interface import Interface - >>> class I1(Interface): pass - ... - >>> - >>> i = I1.interfaces() - >>> x.getName() for x in i - 'I1' - >>> list(i) -
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/changes.rst.txt
Deleted
@@ -1,1 +0,0 @@ -.. include:: ../CHANGES.rst
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/foodforthought.rst.txt
Deleted
@@ -1,71 +0,0 @@ -================================ -Food-based subscription examples -================================ - - -This file gives more subscription examples using a cooking-based example: - -.. doctest:: - - >>> from zope.interface.adapter import AdapterRegistry - >>> registry = AdapterRegistry() - - >>> import zope.interface - >>> class IAnimal(zope.interface.Interface): - ... pass - >>> class IPoultry(IAnimal): - ... pass - >>> class IChicken(IPoultry): - ... pass - >>> class ISeafood(IAnimal): - ... pass - -Adapting to some other interface for which there is no -subscription adapter returns an empty sequence: - -.. doctest:: - - >>> class IRecipe(zope.interface.Interface): - ... pass - >>> class ISausages(IRecipe): - ... pass - >>> class INoodles(IRecipe): - ... pass - >>> class IKFC(IRecipe): - ... pass - - >>> list(registry.subscriptions(IPoultry, IRecipe)) - - -unless we define a subscription: - -.. doctest:: - - >>> registry.subscribe(IAnimal, ISausages, 'sausages') - >>> list(registry.subscriptions(IPoultry, ISausages)) - 'sausages' - -And define another subscription adapter: - -.. doctest:: - - >>> registry.subscribe(IPoultry, INoodles, 'noodles') - >>> meals = list(registry.subscriptions(IPoultry, IRecipe)) - >>> meals.sort() - >>> meals - 'noodles', 'sausages' - - >>> registry.subscribe(IChicken, IKFC, 'kfc') - >>> meals = list(registry.subscriptions(IChicken, IRecipe)) - >>> meals.sort() - >>> meals - 'kfc', 'noodles', 'sausages' - -And the answer for poultry hasn't changed: - -.. doctest:: - - >>> meals = list(registry.subscriptions(IPoultry, IRecipe)) - >>> meals.sort() - >>> meals - 'noodles', 'sausages'
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/hacking.rst.txt
Deleted
@@ -1,312 +0,0 @@ -Hacking on :mod:`zope.interface` -================================ - - -Getting the Code -################ - -The main repository for :mod:`zope.interface` is in the Zope Foundation -Github repository: - - https://github.com/zopefoundation/zope.interface - -You can get a read-only checkout from there: - -.. code-block:: sh - - $ git clone https://github.com/zopefoundation/zope.interface.git - -or fork it and get a writeable checkout of your fork: - -.. code-block:: sh - - $ git clone git@github.com/jrandom/zope.interface.git - -The project also mirrors the trunk from the Github repository as a -Bazaar branch on Launchpad: - -https://code.launchpad.net/zope.interface - -You can branch the trunk from there using Bazaar: - -.. code-block:: sh - - $ bzr branch lp:zope.interface - - -Working in a ``virtualenv`` -########################### - -Running the tests ------------------ - -If you use the ``virtualenv`` package to create lightweight Python -development environments, you can run the tests using nothing more -than the ``python`` binary in a virtualenv. First, create a scratch -environment: - -.. code-block:: sh - - $ /path/to/virtualenv --no-site-packages /tmp/hack-zope.interface - -Next, get this package registered as a "development egg" in the -environment: - -.. code-block:: sh - - $ /tmp/hack-zope.interface/bin/python setup.py develop - -Finally, run the tests using the built-in ``setuptools`` testrunner: - -.. code-block:: sh - - $ /tmp/hack-zope.interface/bin/python setup.py test -q - running test - ... - ---------------------------------------------------------------------- - Ran 2 tests in 0.000s - - OK - -The ``dev`` command alias downloads and installs extra tools, like the -:mod:`nose` testrunner and the :mod:`coverage` coverage analyzer: - -.. code-block:: sh - - $ /tmp/hack-zope.interface/bin/python setup.py dev - $ /tmp/hack-zope.interface/bin/nosetests - running nosetests - .................................... (lots more dots) - ---------------------------------------------------------------------- - Ran 707 tests in 2.166s - - OK - -If you have the :mod:`coverage` package installed in the virtualenv, -you can see how well the tests cover the code: - -.. code-block:: sh - - $ /tmp/hack-zope.interface/bin/nosetests --with coverage - running nosetests - .................................... (lots more dots) - Name Stmts Miss Cover Missing - ---------------------------------------------------------------- - zope.interface 30 0 100% - zope.interface.adapter 440 0 100% - zope.interface.advice 69 0 100% - zope.interface.common 0 0 100% - zope.interface.common.idatetime 98 0 100% - zope.interface.common.interfaces 81 0 100% - zope.interface.common.mapping 32 0 100% - zope.interface.common.sequence 38 0 100% - zope.interface.declarations 312 0 100% - zope.interface.document 54 0 100% - zope.interface.exceptions 21 0 100% - zope.interface.interface 378 0 100% - zope.interface.interfaces 137 0 100% - zope.interface.registry 300 0 100% - zope.interface.ro 25 0 100% - zope.interface.verify 48 0 100% - ---------------------------------------------------------------- - TOTAL 2063 0 100% - ---------------------------------------------------------------------- - Ran 707 tests in 2.166s - - OK - - -Building the documentation --------------------------- - -:mod:`zope.interface` uses the nifty :mod:`Sphinx` documentation system -for building its docs. Using the same virtualenv you set up to run the -tests, you can build the docs: - -The ``docs`` command alias downloads and installs Sphinx and its dependencies: - -.. code-block:: sh - - $ /tmp/hack-zope.interface/bin/python setup.py docs - ... - $ bin/sphinx-build -b html -d docs/_build/doctrees docs docs/_build/html - ... - build succeeded. - - Build finished. The HTML pages are in docs/_build/html. - -You can also test the code snippets in the documentation: - -.. code-block:: sh - - $ bin/sphinx-build -b doctest -d docs/_build/doctrees docs docs/_build/doctest - ... - running tests... - - Document: index - --------------- - 1 items passed all tests: - 17 tests in default - 17 tests in 1 items. - 17 passed and 0 failed. - Test passed. - - Doctest summary - =============== - 17 tests - 0 failures in tests - 0 failures in setup code - build succeeded. - Testing of doctests in the sources finished, look at the \ - results in docs/_build/doctest/output.txt. - - - -Using :mod:`zc.buildout` -######################## - -Setting up the buildout ------------------------ - -:mod:`zope.interface` ships with its own :file:`buildout.cfg` file and -:file:`bootstrap.py` for setting up a development buildout: - -.. code-block:: sh - - $ /path/to/python2.7 bootstrap.py - ... - Generated script '.../bin/buildout' - $ bin/buildout - Develop: '/home/jrandom/projects/Zope/BTK/interface/.' - ... - Generated script '.../bin/sphinx-quickstart'. - Generated script '.../bin/sphinx-build'. - -Running the tests ------------------ - -You can now run the tests: - -.. code-block:: sh - - $ bin/test --all - Running zope.testing.testrunner.layer.UnitTests tests: - Set up zope.testing.testrunner.layer.UnitTests in 0.000 seconds. - Ran 702 tests with 0 failures and 0 errors in 0.000 seconds. - Tearing down left over layers: - Tear down zope.testing.testrunner.layer.UnitTests in 0.000 seconds. - - -Using :mod:`tox` -################ - -Running Tests on Multiple Python Versions ------------------------------------------ - -`tox <http://tox.testrun.org/latest/>`_ is a Python-based test automation -tool designed to run tests against multiple Python versions. It creates -a ``virtualenv`` for each configured version, installs the current package -and configured dependencies into each ``virtualenv``, and then runs the -configured commands. - -:mod:`zope.interface` configures the following :mod:`tox` environments via -its ``tox.ini`` file: - -- The defined Python environments build a ``virtualenv`` with various Python 2, - Python 3, PyPy 2 and PyPy 3 versions, install :mod:`zope.interface` and - dependencies, and run the tests via ``python setup.py test -q``. - -- The ``coverage`` environment builds a ``virtualenv`` with ``python2.7``, - installs :mod:`zope.interface` and dependencies, installs - :mod:`nose` and :mod:`coverage`, and runs ``nosetests`` with statement - coverage. - -- The ``docs`` environment builds a virtualenv with ``python2.7``, installs - :mod:`zope.interface` and dependencies, installs ``Sphinx`` and - dependencies, and then builds the docs and exercises the doctest snippets. - -This example requires that you have a working ``python2.7`` on your path, -as well as installing ``tox``: - -.. code-block:: sh - - $ tox -e py26 - GLOB sdist-make: .../zope.interface/setup.py - py26 sdist-reinst: .../zope.interface/.tox/dist/zope.interface-4.0.2dev.zip - py26 runtests: commands0 - ... - ---------------------------------------------------------------------- - Ran 1341 tests in 0.477s - - OK - ___________________________________ summary ____________________________________ - py26: commands succeeded - congratulations :) - -Running ``tox`` with no arguments runs all the configured environments, -including building the docs and testing their snippets: - -.. code-block:: sh - - $ tox - GLOB sdist-make: .../zope.interface/setup.py - py26 sdist-reinst: .../zope.interface/.tox/dist/zope.interface-4.0.2dev.zip - py26 runtests: commands0 - ... - Doctest summary - =============== - 678 tests - 0 failures in tests - 0 failures in setup code - 0 failures in cleanup code - build succeeded. - ___________________________________ summary ____________________________________ - py26: commands succeeded - py27: commands succeeded - py32: commands succeeded - pypy: commands succeeded - coverage: commands succeeded - docs: commands succeeded - congratulations :) - - -Contributing to :mod:`zope.interface` -##################################### - -Submitting a Bug Report ------------------------ - -:mod:`zope.interface` tracks its bugs on Github: - - https://github.com/zopefoundation/zope.interface/issues - -Please submit bug reports and feature requests there. - - -Sharing Your Changes --------------------- - -.. note:: - - Please ensure that all tests are passing before you submit your code. - If possible, your submission should include new tests for new features - or bug fixes, although it is possible that you may have tested your - new code by updating existing tests. - -If have made a change you would like to share, the best route is to fork -the Githb repository, check out your fork, make your changes on a branch -in your fork, and push it. You can then submit a pull request from your -branch: - - https://github.com/zopefoundation/zope.interface/pulls - -If you branched the code from Launchpad using Bazaar, you have another -option: you can "push" your branch to Launchpad: - -.. code-block:: sh - - $ bzr push lp:~jrandom/zope.interface/cool_feature - -After pushing your branch, you can link it to a bug report on Launchpad, -or request that the maintainers merge your branch using the Launchpad -"merge request" feature.
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/human.rst.txt
Deleted
@@ -1,180 +0,0 @@ -========================== -Using the Adapter Registry -========================== - -This is a small demonstration of the :mod:`zope.interface` package including its -adapter registry. It is intended to provide a concrete but narrow example on -how to use interfaces and adapters outside of Zope 3. - -First we have to import the interface package: - -.. doctest:: - - >>> import zope.interface - -We now develop an interface for our object, which is a simple file in this -case. For now we simply support one attribute, the body, which contains the -actual file contents: - -.. doctest:: - - >>> class IFile(zope.interface.Interface): - ... - ... body = zope.interface.Attribute('Contents of the file.') - ... - -For statistical reasons we often want to know the size of a file. However, it -would be clumsy to implement the size directly in the file object, since the -size really represents meta-data. Thus we create another interface that -provides the size of something: - -.. doctest:: - - >>> class ISize(zope.interface.Interface): - ... - ... def getSize(): - ... 'Return the size of an object.' - ... - -Now we need to implement the file interface. It is essential that the object states -that it implements the ``IFile`` interface. We also provide a default body -value (just to make things simpler for this example): - -.. doctest:: - - >>> @zope.interface.implementer(IFile) - ... class File(object): - ... - ... body = 'foo bar' - ... - -Next we implement an adapter that can provide the ``ISize`` interface given any -object providing ``IFile``. By convention we use ``__used_for__`` to specify the -interface that we expect the adapted object to provide, in our case -``IFile``. However, this attribute is not used for anything. If you have -multiple interfaces for which an adapter is used, just specify the interfaces -via a tuple. - -Again by convention, the constructor of an adapter takes one argument, the -context. The context in this case is an instance of ``File`` (providing ``IFile``) -that is used to extract the size from. Also by convention the context is -stored in an attribute named ``context`` on the adapter. The `twisted`_ community -refers to the context as the ``original`` object. However, you may feel free to -use a specific argument name, such as ``file``: - -.. doctest:: - - >>> @zope.interface.implementer(ISize) - ... class FileSize(object): - ... - ... __used_for__ = IFile - ... - ... def __init__(self, context): - ... self.context = context - ... - ... def getSize(self): - ... return len(self.context.body) - ... - -Now that we have written our adapter, we have to register it with an adapter -registry, so that it can be looked up when needed. There is no such thing as a -global registry; thus we have to instantiate one for our example manually: - -.. doctest:: - - >>> from zope.interface.adapter import AdapterRegistry - >>> registry = AdapterRegistry() - - -The registry keeps a map of what adapters implement based on another -interface the object already provides. Therefore, we next have to register an -adapter that adapts from ``IFile`` to ``ISize``. The first argument to -the registry's ``register()`` method is a list of original interfaces.In our -cause we have only one original interface, ``IFile``. A list makes sense, since -the interface package has the concept of multi-adapters, which are adapters -that require multiple objects to adapt to a new interface. In these -situations, your adapter constructor will require an argument for each -specified interface. - -The second argument is the interface the adapter provides, in our case -``ISize``. The third argument is the name of the adapter. Since we do not care -about names, we simply leave it as an empty string. Names are commonly useful, -if you have adapters for the same set of interfaces, but they are useful in -different situations. The last argument is simply the adapter class: - -.. doctest:: - - >>> registry.register(IFile, ISize, '', FileSize) - -You can now use the the registry to lookup the adapter: - -.. doctest:: - - >>> registry.lookup1(IFile, ISize, '') - <class 'FileSize'> - -Let's get a little bit more practical. Let's create a ``File`` instance and -create the adapter using a registry lookup. Then we see whether the adapter -returns the correct size by calling ``getSize()``: - -.. doctest:: - - >>> file = File() - >>> size = registry.lookup1(IFile, ISize, '')(file) - >>> size.getSize() - 7 - -However, this is not very practical, since I have to manually pass in the -arguments to the lookup method. There is some syntactic candy that will allow -us to get an adapter instance by simply calling ``ISize(file)``. To make use of -this functionality, we need to add our registry to the ``adapter_hooks`` list, -which is a member of the adapters module. This list stores a collection of -callables that are automatically invoked when ``IFoo(obj)`` is called; their -purpose is to locate adapters that implement an interface for a certain -context instance. - -You are required to implement your own adapter hook; this example covers one -of the simplest hooks that use the registry, but you could implement one that -used an adapter cache or persistent adapters, for instance. The helper hook is -required to expect as first argument the desired output interface (for us -``ISize``) and as the second argument the context of the adapter (here -``file``). The function returns an adapter, i.e. a ``FileSize`` instance: - -.. doctest:: - - >>> def hook(provided, object): - ... adapter = registry.lookup1(zope.interface.providedBy(object), - ... provided, '') - ... return adapter(object) - ... - -We now just add the hook to an ``adapter_hooks`` list: - -.. doctest:: - - >>> from zope.interface.interface import adapter_hooks - >>> adapter_hooks.append(hook) - -Once the hook is registered, you can use the desired syntax: - -.. doctest:: - - >>> size = ISize(file) - >>> size.getSize() - 7 - -Now we have to clean up after ourselves, so that others after us have a clean -``adapter_hooks`` list: - -.. doctest:: - - >>> adapter_hooks.remove(hook) - -That's it. I have intentionally left out a discussion of named adapters and -multi-adapters, since this text is intended as a practical and simple -introduction to Zope 3 interfaces and adapters. You might want to read the -``adapter.txt`` in the ``zope.interface`` package for a more formal, referential -and complete treatment of the package. Warning: People have reported that -``adapter.txt`` makes their brain feel soft! - -.. _twisted: https://twistedmatrix.com/
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/human.ru.rst.txt
Deleted
@@ -1,156 +0,0 @@ -=============================== -Использование реестра адаптеров -=============================== - -Данный документ содержит небольшую демонстрацию пакета ``zope.interface`` и его -реестра адаптеров. Документ рассчитывался как конкретный, но более узкий пример -того как использовать интерфейсы и адаптеры вне Zope 3. - -Сначала нам необходимо импортировать пакет для работы с интерфейсами:: - - >>> import zope.interface - -Теперь мы разработаем интерфейс для нашего объекта - простого файла. Наш файл -будет содержать всего один атрибут - body, в котором фактически будет сохранено -содержимое файла:: - - >>> class IFile(zope.interface.Interface): - ... - ... body = zope.interface.Attribute(u'Содержимое файла.') - ... - -Для статистики нам часто необходимо знать размер файла. Но было бы несколько -топорно реализовывать определение размера прямо для объекта файла, т.к. размер -больше относится к мета-данным. Таким образом мы создаем еще один интерфейс для -представления размера какого-либо объекта:: - - >>> class ISize(zope.interface.Interface): - ... - ... def getSize(): - ... 'Return the size of an object.' - ... - -Теперь мы должны создать класс реализующий наш файл. Необходимо что бы наш -объект хранил информацию о том, что он реализует интерфейс `IFile`. Мы также -создаем атрибут с содержимым файла по умолчанию (для упрощения нашего -примера):: - - >>> class File(object): - ... - ... zope.interface.implements(IFile) - ... body = 'foo bar' - ... - -Дальше мы создаем адаптер, который будет предоставлять интерфейс `ISize` -получая любой объект предоставляющий интерфейс `IFile`. По соглашению мы -используем атрибут `__used_for__` для указания интерфейса который как мы -ожидаем предоставляет адаптируемый объект, `IFile` в нашем случае. На самом -деле этот атрибут используется только для документирования. В случае если -адаптер используется для нескольких интерфейсов можно указать их все в виде -кортежа. - -Опять же по соглашению конструктор адаптера получает один аргумент - context -(контекст). В нашем случае контекст - это экземпляр `IFile` (объект, -предоставляющий `IFile`) который используется для получения из него размера. -Так же по соглашению контекст сохраняется а адаптере в атрибуте с именем -`context`. Twisted комьюнити ссылается на контекст как на объект `original`. -Таким образом можно также дать аргументу любое подходящее имя, например -`file`:: - - >>> class FileSize(object): - ... - ... zope.interface.implements(ISize) - ... __used_for__ = IFile - ... - ... def __init__(self, context): - ... self.context = context - ... - ... def getSize(self): - ... return len(self.context.body) - ... - -Теперь когда мы написали наш адаптер мы должны зарегистрировать его в реестре -адаптеров, что бы его можно было запросить когда он понадобится. Здесь нет -какого-либо глобального реестра адаптеров, таким образом мы должны -самостоятельно создать для нашего примера реестр:: - - >>> from zope.interface.adapter import AdapterRegistry - >>> registry = AdapterRegistry() - -Реестр содержит отображение того, что адаптер реализует на основе другого -интерфейса который предоставляет объект. Поэтому дальше мы регистрируем адаптер -который адаптирует интерфейс `IFile` к интерфейсу `ISize`. Первый аргумент к -методу `register()` реестра - это список адаптируемых интерфейсов. В нашем -случае мы имеем только один адаптируемый интерфейс - `IFile`. Список -интерфейсов имеет смысл для использования концепции мульти-адаптеров, которые -требуют нескольких оригинальных объектов для адаптации к новому интерфейсу. В -этой ситуации конструктор адаптера будет требовать новый аргумент для каждого -оригинального интерфейса. - -Второй аргумент метода `register()` - это интерфейс который предоставляет -адаптер, в нашем случае `ISize`. Третий аргумент - имя адаптера. Сейчас нам не -важно имя адаптера и мы передаем его как пустую строку. Обычно имена полезны -если используются адаптеры для одинакового набора интерфейсов, но в различных -ситуациях. Последний аргумент - это класс адаптера:: - - >>> registry.register(IFile, ISize, '', FileSize) - -Теперь мы можем использовать реестр для запроса адаптера:: - - >>> registry.lookup1(IFile, ISize, '') - <class '__main__.FileSize'> - -Попробуем более практичный пример. Создадим экземпляр `File` и создадим адаптер -использующий запрос реестра. Затем мы увидим возвращает ли адаптер корректный -размер при вызове `getSize()`:: - - >>> file = File() - >>> size = registry.lookup1(IFile, ISize, '')(file) - >>> size.getSize() - 7 - -На самом деле это не очень практично, т.к. нам нужно самим передавать все -аргументы методу запроса. Существует некоторый синтаксический леденец который -позволяет нам получить экземпляр адаптера просто вызвав `ISize(file)`. Что бы -использовать эту функциональность нам понадобится добавить наш реестр к списку -adapter_hooks, который находится в модуле с адаптерами. Этот список хранит -коллекцию вызываемых объектов которые вызываются автоматически когда вызывается -IFoo(obj); их предназначение - найти адаптеры которые реализуют интерфейс для -определенного экземпляра контекста. - -Необходимо реализовать свою собственную функцию для поиска адаптера; данный -пример описывает одну из простейших функций для использования с реестром, но -также можно реализовать поисковые функции которые, например, используют -кэширование, или адаптеры сохраняемые в базе. Функция поиска должна принимать -желаемый на выходе интерфейс (в нашем случае `ISize`) как первый аргумент и -контекст для адаптации (`file`) как второй. Функция должна вернуть адаптер, -т.е. экземпляр `FileSize`:: - - >>> def hook(provided, object): - ... adapter = registry.lookup1(zope.interface.providedBy(object), - ... provided, '') - ... return adapter(object) - ... - -Теперь мы просто добавляем нашу функцию к списку `adapter_hooks`:: - - >>> from zope.interface.interface import adapter_hooks - >>> adapter_hooks.append(hook) - -Как только функция зарегистрирована мы можем использовать желаемый синтаксис:: - - >>> size = ISize(file) - >>> size.getSize() - 7 - -После нам нужно прибраться за собой, что бы другие получили чистый список -`adaper_hooks` после нас:: - - >>> adapter_hooks.remove(hook) - -Это все. Здесь намеренно отложена дискуссия об именованных и мульти-адаптерах, -т.к. данный текст рассчитан как практическое и простое введение в интерфейсы и -адаптеры Zope 3. Для более подробной информации имеет смысл прочитать -`adapter.txt` из пакета `zope.interface`, что бы получить более формальное, -справочное и полное трактование пакета. Внимание: многие жаловались, что -`adapter.txt` приводит их мозг к расплавленному состоянию!
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/index.rst.txt
Deleted
@@ -1,40 +0,0 @@ -.. zope.interface documentation master file, created by - sphinx-quickstart on Mon Mar 26 16:31:31 2012. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. - -Welcome to zope.interface's documentation! -========================================== - -Contents: - -.. toctree:: - :maxdepth: 2 - - README - adapter - human - verify - foodforthought - api/index - hacking - changes - -По-русски -========= - -.. toctree:: - :maxdepth: 2 - - README.ru - adapter.ru - human.ru - - - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search`
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/_build/html/_sources/verify.rst.txt
Deleted
@@ -1,322 +0,0 @@ -===================================== - Verifying interface implementations -===================================== - -The ``zope.interface.verify`` module provides functions that test whether a -given interface is implemented by a class or provided by an object. - -.. currentmodule:: zope.interface.verify - -Verifying objects -================= - -.. autofunction:: verifyObject - -.. autoexception:: zope.interface.Invalid - -Let's demonstrate. We'll begin by defining a simple interface hierarchy -requiring two attributes, and a helper method that will instantiate and verify -that an object provides this interface. - -.. doctest:: - - >>> from zope.interface import Interface, Attribute, implementer - >>> from zope.interface import Invalid - >>> from zope.interface.verify import verifyObject - >>> oname, __name__ = __name__, 'base' # Pretend we're in a module, not a doctest - >>> class IBase(Interface): - ... x = Attribute("The X attribute") - >>> __name__ = 'module' # Pretend to be a different module. - >>> class IFoo(IBase): - ... y = Attribute("The Y attribute") - >>> __name__ = oname; del oname - >>> class Foo(object): - ... pass - >>> def verify_foo(**kwargs): - ... foo = Foo() - ... try: - ... return verifyObject(IFoo, foo, **kwargs) - ... except Invalid as e: - ... print(e) - -If we try to verify an instance of this ``Foo`` class, three errors -will be reported. The declarations (does the object provide ``IFoo``) -are checked, as are the attributes specified in the interface being -validated (and its ancestors). Notice that the interface being -verified is shown, as is the interface where the attribute was -defined. - -.. doctest:: - - >>> verify_foo() - The object <Foo...> has failed to implement interface ...IFoo: - Does not declaratively implement the interface - The base.IBase.x attribute was not provided - The module.IFoo.y attribute was not provided - -If we add the two missing attributes, we still have the error about not -declaring the correct interface. - -.. doctest:: - - >>> Foo.x = Foo.y = 42 - >>> verify_foo() - The object <Foo...> has failed to implement interface ...IFoo: Does not declaratively implement the interface. - -If we want to only check the structure of the object, without examining -its declarations, we can use the ``tentative`` argument. - -.. doctest:: - - >>> verify_foo(tentative=True) - True - -Of course, we can always mark a particular instance as providing the -desired interface. - -.. doctest:: - - >>> from zope.interface import alsoProvides - >>> foo = Foo() - >>> alsoProvides(foo, IFoo) - >>> verifyObject(IFoo, foo) - True - -If all instances will provide the interface, we can -mark a class as implementing it. But we have to remove the interface from the -instance first so a consistent interface resolution order can be achieved. -(Calling ``gc.collect()`` is also necessary because we use weakrefs.) - -.. doctest:: - - >>> from zope.interface import classImplements - >>> from zope.interface import noLongerProvides - >>> import gc - >>> noLongerProvides(foo, IFoo) - >>> _ = gc.collect() - >>> classImplements(Foo, IFoo) - >>> verify_foo() - True - - -Testing for attributes ----------------------- - -Attributes of the object, be they defined by its class or added by its -``__init__`` method, will be recognized: - -.. doctest:: - - >>> @implementer(IFoo) - ... class Foo(object): - ... x = 1 - ... def __init__(self): - ... self.y = 2 - - >>> verifyObject(IFoo, Foo()) - True - -If either attribute is missing, verification will fail by raising an -exception. - -.. doctest:: - - >>> @implementer(IFoo) - ... class Foo(object): - ... x = 1 - >>> verify_foo() - The object <Foo...> has failed to implement interface ...IFoo: The module.IFoo.y attribute was not provided. - >>> @implementer(IFoo) - ... class Foo(object): - ... def __init__(self): - ... self.y = 2 - >>> verify_foo() - The object <Foo...> has failed to implement interface ...IFoo: The base.IBase.x attribute was not provided. - -If both attributes are missing, an exception is raised reporting -both errors. - -.. doctest:: - - >>> @implementer(IFoo) - ... class Foo(object): - ... pass - >>> verify_foo() - The object <Foo ...> has failed to implement interface ...IFoo: - The base.IBase.x attribute was not provided - The module.IFoo.y attribute was not provided - -If an attribute is implemented as a property that raises an ``AttributeError`` -when trying to get its value, the attribute is considered missing: - -.. doctest:: - - >>> oname, __name__ = __name__, 'module' - >>> class IFoo(Interface): - ... x = Attribute('The X attribute') - >>> __name__ = oname; del oname - >>> @implementer(IFoo) - ... class Foo(object): - ... @property - ... def x(self): - ... raise AttributeError - >>> verify_foo() - The object <Foo...> has failed to implement interface ...IFoo: The module.IFoo.x attribute was not provided. - - -Any other exception raised by a property will propagate to the caller of -``verifyObject``: - -.. doctest:: - - >>> @implementer(IFoo) - ... class Foo(object): - ... @property - ... def x(self): - ... raise Exception - >>> verify_foo() - Traceback (most recent call last): - Exception - -Of course, broken properties that are not required by the interface don't do -any harm: - -.. doctest:: - - >>> @implementer(IFoo) - ... class Foo(object): - ... x = 1 - ... @property - ... def y(self): - ... raise Exception - >>> verify_foo() - True - - -Testing For Methods -------------------- - -Methods are also validated to exist. We'll start by defining a method -that takes one argument. If we don't provide it, we get an error. - -.. doctest:: - - >>> oname, __name__ = __name__, 'module' - >>> class IFoo(Interface): - ... def simple(arg1): "Takes one positional argument" - >>> __name__ = oname; del oname - >>> @implementer(IFoo) - ... class Foo(object): - ... pass - >>> verify_foo() - The object <Foo...> has failed to implement interface ...IFoo: The module.IFoo.simple(arg1) attribute was not provided. - -Once they exist, they are checked to be callable, and for compatible signatures. - -Not being callable is an error. - -.. doctest:: - - >>> Foo.simple = 42 - >>> verify_foo() - The object <Foo...> has failed to implement interface ...IFoo: The contract of module.IFoo.simple(arg1) is violated because '42' is not a method. - -Taking too few arguments is an error. (Recall that the ``self`` -argument is implicit.) - -.. doctest:: - - >>> Foo.simple = lambda self: "I take no arguments" - >>> verify_foo() - The object <Foo...> has failed to implement interface ...IFoo: The contract of module.IFoo.simple(arg1) is violated because '<lambda>()' doesn't allow enough arguments. - -Requiring too many arguments is an error. - -.. doctest:: - - >>> Foo.simple = lambda self, a, b: "I require two arguments" - >>> verify_foo() - The object <Foo...> has failed to implement interface ...IFoo: The contract of module.IFoo.simple(arg1) is violated because '<lambda>(a, b)' requires too many arguments. - -Variable arguments can be used to implement the required number, as -can arguments with defaults. - -.. doctest:: - - >>> Foo.simple = lambda self, *args: "Varargs work." - >>> verify_foo() - True - >>> Foo.simple = lambda self, a=1, b=2: "Default args work." - >>> verify_foo() - True - -If our interface defines a method that uses variable positional or -variable keyword arguments, the implementation must also accept them. - -.. doctest:: - - >>> oname, __name__ = __name__, 'module' - >>> class IFoo(Interface): - ... def needs_kwargs(**kwargs): pass - >>> __name__ = oname; del oname - >>> @implementer(IFoo) - ... class Foo(object): - ... def needs_kwargs(self, a=1, b=2): pass - >>> verify_foo() - The object <Foo...> has failed to implement interface ...IFoo: The contract of module.IFoo.needs_kwargs(**kwargs) is violated because 'Foo.needs_kwargs(a=1, b=2)' doesn't support keyword arguments. - - >>> oname, __name__ = __name__, 'module' - >>> class IFoo(Interface): - ... def needs_varargs(*args): pass - >>> __name__ = oname; del oname - >>> @implementer(IFoo) - ... class Foo(object): - ... def needs_varargs(self, **kwargs): pass - >>> verify_foo() - The object <Foo...> has failed to implement interface ...IFoo: The contract of module.IFoo.needs_varargs(*args) is violated because 'Foo.needs_varargs(**kwargs)' doesn't support variable arguments. - -Of course, missing attributes are also found and reported, and the -source interface of the missing attribute is included. Similarly, when -the failing method is from a parent class, that is also reported. - -.. doctest:: - - >>> oname, __name__ = __name__, 'base' - >>> class IBase(Interface): - ... def method(arg1): "Takes one positional argument" - >>> __name__ = 'module' - >>> class IFoo(IBase): - ... x = Attribute('The X attribute') - >>> __name__ = oname; del oname - >>> class Base(object): - ... def method(self): "I don't have enough arguments" - >>> @implementer(IFoo) - ... class Foo(Base): - ... pass - >>> verify_foo() - The object <Foo...> has failed to implement interface ...IFoo: - The contract of base.IBase.method(arg1) is violated because 'Base.method()' doesn't allow enough arguments - The module.IFoo.x attribute was not provided - -Verifying Classes -================= - -The function `verifyClass` is used to check that a class implements -an interface properly, meaning that its instances properly provide the -interface. Many of the same things that `verifyObject` checks can be -checked for classes, but certain conditions, such as the presence of -attributes, cannot be verified. - -.. autofunction:: verifyClass - -.. doctest:: - - >>> from zope.interface.verify import verifyClass - >>> def verify_foo_class(): - ... try: - ... return verifyClass(IFoo, Foo) - ... except Invalid as e: - ... print(e) - - >>> verify_foo_class() - The object <class 'Foo'> has failed to implement interface ...IFoo: The contract of base.IBase.method(arg1) is violated because 'Base.method(self)' doesn't allow enough arguments.
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/.manylinux-install.sh -> _service:tar_scm:zope.interface-6.0.tar.gz/.manylinux-install.sh
Changed
@@ -28,9 +28,7 @@ tox_env_map() { case $1 in - *"cp27"*) echo 'py27';; - *"cp35"*) echo 'py35';; - *"cp36"*) echo 'py36';; + *"cp312"*) echo 'py312';; *"cp37"*) echo 'py37';; *"cp38"*) echo 'py38';; *"cp39"*) echo 'py39';; @@ -43,16 +41,19 @@ # Compile wheels for PYBIN in /opt/python/*/bin; do if \ - "${PYBIN}" == *"cp27"* || \ - "${PYBIN}" == *"cp35"* || \ + "${PYBIN}" == *"cp312"* || \ "${PYBIN}" == *"cp311"* || \ - "${PYBIN}" == *"cp36"* || \ "${PYBIN}" == *"cp37"* || \ "${PYBIN}" == *"cp38"* || \ "${PYBIN}" == *"cp39"* || \ "${PYBIN}" == *"cp310"* ; then - "${PYBIN}/pip" install -e /io/ - "${PYBIN}/pip" wheel /io/ -w wheelhouse/ + if "${PYBIN}" == *"cp312"* ; then + "${PYBIN}/pip" install --pre -e /io/ + "${PYBIN}/pip" wheel /io/ --pre -w wheelhouse/ + else + "${PYBIN}/pip" install -e /io/ + "${PYBIN}/pip" wheel /io/ -w wheelhouse/ + fi if `uname -m` == 'aarch64' ; then cd /io/ ${PYBIN}/pip install tox
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/CHANGES.rst -> _service:tar_scm:zope.interface-6.0.tar.gz/CHANGES.rst
Changed
@@ -2,6 +2,24 @@ Changes ========= +6.0 (2023-03-17) +================ + +- Build Linux binary wheels for Python 3.11. + +- Drop support for Python 2.7, 3.5, 3.6. + +- Fix test deprecation warning on Python 3.11. + +- Add preliminary support for Python 3.12 as of 3.12a5. + +- Drop: + + + `zope.interface.implements` + + `zope.interface.implementsOnly` + + `zope.interface.classProvides` + + 5.5.2 (2022-11-17) ==================
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/PKG-INFO -> _service:tar_scm:zope.interface-6.0.tar.gz/PKG-INFO
Changed
@@ -1,6 +1,6 @@ Metadata-Version: 2.1 Name: zope.interface -Version: 5.5.2 +Version: 6.0 Summary: Interfaces for Python Home-page: https://github.com/zopefoundation/zope.interface Author: Zope Foundation and Contributors @@ -12,11 +12,7 @@ Classifier: License :: OSI Approved :: Zope Public License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 2 -Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.5 -Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 @@ -26,7 +22,7 @@ Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Framework :: Zope :: 3 Classifier: Topic :: Software Development :: Libraries :: Python Modules -Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.* +Requires-Python: >=3.7 Provides-Extra: docs Provides-Extra: test Provides-Extra: testing @@ -68,6 +64,24 @@ Changes ========= +6.0 (2023-03-17) +================ + +- Build Linux binary wheels for Python 3.11. + +- Drop support for Python 2.7, 3.5, 3.6. + +- Fix test deprecation warning on Python 3.11. + +- Add preliminary support for Python 3.12 as of 3.12a5. + +- Drop: + + + `zope.interface.implements` + + `zope.interface.implementsOnly` + + `zope.interface.classProvides` + + 5.5.2 (2022-11-17) ==================
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/appveyor.yml -> _service:tar_scm:zope.interface-6.0.tar.gz/appveyor.yml
Changed
@@ -10,14 +10,14 @@ secure: aoZC/+rvJKg8B5GMGIxd1X2q2bz7SMl8G3810BID9U8PXFqM0FbWaK9fZ9qcU0UyG2xJsK56Fb6+L6g27I0Lg8UFNhlU1zLAuMSgJQbHsqawFgSY067IdJB68pp34d/oEyxMrJvAKENHH77Fe4KGDssLlk5WnnYS3DA9b66p5imP+1DTtkq5/gMtoG4nZTBtVos7J2kkYTQ5t4BjzTQxPMC3bStNnvuuB0orX4AoCyTrOR1wdZFiNKLzbVnrJCNn24t/n3kG9WrxbnKlrbOm4A== matrix: - - python: 27-x64 - - python: 35-x64 - - python: 36-x64 - python: 37-x64 - python: 38-x64 - python: 39-x64 - python: 310-x64 - python: 311-x64 + # `multibuild` cannot install non-final versions as they are not on + # ftp.python.org, so we skip Python 3.11 until its final release: + # - python: 312-x64 install: - "SET PYTHONVERSION=%PYTHON%"
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/docs/api/declarations.rst -> _service:tar_scm:zope.interface-6.0.tar.gz/docs/api/declarations.rst
Changed
@@ -515,33 +515,6 @@ provided. -Deprecated Functions --------------------- - -implements -~~~~~~~~~~ - -.. caution:: Does not work on Python 3. Use the `implementer` decorator instead. - -.. autofunction:: implements - - -implementsOnly -~~~~~~~~~~~~~~ - -.. caution:: Does not work on Python 3. Use the `implementer_only` decorator instead. - -.. autofunction:: implementsOnly - - -classProvides -~~~~~~~~~~~~~ - -.. caution:: Does not work on Python 3. Use the `provider` decorator instead. - -.. autofunction:: classProvides - - Querying The Interfaces Of Objects ==================================
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/setup.cfg -> _service:tar_scm:zope.interface-6.0.tar.gz/setup.cfg
Changed
@@ -1,5 +1,5 @@ bdist_wheel -universal = 1 +universal = 0 zest.releaser create-wheel = no @@ -21,7 +21,7 @@ force_single_line = True combine_as_imports = True sections = FUTURE,STDLIB,THIRDPARTY,ZOPE,FIRSTPARTY,LOCALFOLDER -known_third_party = six, docutils, pkg_resources +known_third_party = six, docutils, pkg_resources, pytz known_zope = known_first_party = default_section = ZOPE
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/setup.py -> _service:tar_scm:zope.interface-6.0.tar.gz/setup.py
Changed
@@ -100,7 +100,7 @@ ) setup(name='zope.interface', - version='5.5.2', + version='6.0', url='https://github.com/zopefoundation/zope.interface', license='ZPL 2.1', description='Interfaces for Python', @@ -113,11 +113,7 @@ "License :: OSI Approved :: Zope Public License", "Operating System :: OS Independent", "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.5", - "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", @@ -139,14 +135,7 @@ zip_safe=False, tests_require=tests_require, install_requires='setuptools', - python_requires=', '.join( - '>=2.7', - '!=3.0.*', - '!=3.1.*', - '!=3.2.*', - '!=3.3.*', - '!=3.4.*', - ), + python_requires='>=3.7', extras_require={ 'docs': 'Sphinx', 'repoze.sphinx.autointerface', 'test': tests_require,
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope.interface.egg-info/PKG-INFO -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope.interface.egg-info/PKG-INFO
Changed
@@ -1,6 +1,6 @@ Metadata-Version: 2.1 Name: zope.interface -Version: 5.5.2 +Version: 6.0 Summary: Interfaces for Python Home-page: https://github.com/zopefoundation/zope.interface Author: Zope Foundation and Contributors @@ -12,11 +12,7 @@ Classifier: License :: OSI Approved :: Zope Public License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 2 -Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.5 -Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 @@ -26,7 +22,7 @@ Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Framework :: Zope :: 3 Classifier: Topic :: Software Development :: Libraries :: Python Modules -Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.* +Requires-Python: >=3.7 Provides-Extra: docs Provides-Extra: test Provides-Extra: testing @@ -68,6 +64,24 @@ Changes ========= +6.0 (2023-03-17) +================ + +- Build Linux binary wheels for Python 3.11. + +- Drop support for Python 2.7, 3.5, 3.6. + +- Fix test deprecation warning on Python 3.11. + +- Add preliminary support for Python 3.12 as of 3.12a5. + +- Drop: + + + `zope.interface.implements` + + `zope.interface.implementsOnly` + + `zope.interface.classProvides` + + 5.5.2 (2022-11-17) ==================
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope.interface.egg-info/SOURCES.txt -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope.interface.egg-info/SOURCES.txt
Changed
@@ -29,25 +29,6 @@ docs/index.rst docs/make.bat docs/verify.rst -docs/_build/doctest/output.txt -docs/_build/html/_sources/README.rst.txt -docs/_build/html/_sources/README.ru.rst.txt -docs/_build/html/_sources/adapter.rst.txt -docs/_build/html/_sources/adapter.ru.rst.txt -docs/_build/html/_sources/changes.rst.txt -docs/_build/html/_sources/foodforthought.rst.txt -docs/_build/html/_sources/hacking.rst.txt -docs/_build/html/_sources/human.rst.txt -docs/_build/html/_sources/human.ru.rst.txt -docs/_build/html/_sources/index.rst.txt -docs/_build/html/_sources/verify.rst.txt -docs/_build/html/_sources/api/adapters.rst.txt -docs/_build/html/_sources/api/common.rst.txt -docs/_build/html/_sources/api/components.rst.txt -docs/_build/html/_sources/api/declarations.rst.txt -docs/_build/html/_sources/api/index.rst.txt -docs/_build/html/_sources/api/ro.rst.txt -docs/_build/html/_sources/api/specifications.rst.txt docs/api/adapters.rst docs/api/common.rst docs/api/components.rst
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/__init__.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/__init__.py
Changed
@@ -62,14 +62,11 @@ from zope.interface.declarations import classImplements from zope.interface.declarations import classImplementsFirst from zope.interface.declarations import classImplementsOnly -from zope.interface.declarations import classProvides from zope.interface.declarations import directlyProvidedBy from zope.interface.declarations import directlyProvides from zope.interface.declarations import implementedBy from zope.interface.declarations import implementer from zope.interface.declarations import implementer_only -from zope.interface.declarations import implements -from zope.interface.declarations import implementsOnly from zope.interface.declarations import moduleProvides from zope.interface.declarations import named from zope.interface.declarations import noLongerProvides
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/_compat.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/_compat.py
Changed
@@ -20,51 +20,16 @@ """ import os import sys -import types -if sys.version_info0 < 3: - def _normalize_name(name): - if isinstance(name, basestring): - return unicode(name) - raise TypeError("name must be a regular or unicode string") - - CLASS_TYPES = (type, types.ClassType) - STRING_TYPES = (basestring,) - - _BUILTINS = '__builtin__' - - PYTHON3 = False - PYTHON2 = True - -else: - - def _normalize_name(name): - if isinstance(name, bytes): - name = str(name, 'ascii') - if isinstance(name, str): - return name - raise TypeError("name must be a string or ASCII-only bytes") - - CLASS_TYPES = (type,) - STRING_TYPES = (str,) - - _BUILTINS = 'builtins' - - PYTHON3 = True - PYTHON2 = False +def _normalize_name(name): + if isinstance(name, bytes): + name = str(name, 'ascii') + if isinstance(name, str): + return name + raise TypeError("name must be a string or ASCII-only bytes") PYPY = hasattr(sys, 'pypy_version_info') -PYPY2 = PYTHON2 and PYPY - -def _skip_under_py3k(test_method): - import unittest - return unittest.skipIf(sys.version_info0 >= 3, "Only on Python 2")(test_method) - - -def _skip_under_py2(test_method): - import unittest - return unittest.skipIf(sys.version_info0 < 3, "Only on Python 3")(test_method) def _c_optimizations_required():
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/_zope_interface_coptimizations.c -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/_zope_interface_coptimizations.c
Changed
@@ -31,12 +31,7 @@ #define Py_TYPE(o) ((o)->ob_type) #endif -#if PY_MAJOR_VERSION >= 3 -#define PY3K #define PyNative_FromString PyUnicode_FromString -#else -#define PyNative_FromString PyString_FromString -#endif static PyObject *str__dict__, *str__implemented__, *strextends; static PyObject *BuiltinImplementationSpecifications, *str__provides__; @@ -763,10 +758,6 @@ return Py_None; } -#ifndef PY3K -typedef long Py_hash_t; -#endif - typedef struct { Spec spec; PyObject* __name__; @@ -1255,11 +1246,7 @@ { PyObject *result, *key, *cache; result = key = cache = NULL; -#ifdef PY3K if ( name && !PyUnicode_Check(name) ) -#else - if ( name && !PyString_Check(name) && !PyUnicode_Check(name) ) -#endif { PyErr_SetString(PyExc_ValueError, "name is not a string or unicode"); @@ -1351,11 +1338,7 @@ { PyObject *result, *cache; -#ifdef PY3K if ( name && !PyUnicode_Check(name) ) -#else - if ( name && !PyString_Check(name) && !PyUnicode_Check(name) ) -#endif { PyErr_SetString(PyExc_ValueError, "name is not a string or unicode"); @@ -1427,11 +1410,7 @@ { PyObject *required, *factory, *result; -#ifdef PY3K if ( name && !PyUnicode_Check(name) ) -#else - if ( name && !PyString_Check(name) && !PyUnicode_Check(name) ) -#endif { PyErr_SetString(PyExc_ValueError, "name is not a string or unicode");
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/adapter.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/adapter.py
Changed
@@ -23,7 +23,6 @@ from zope.interface.interfaces import IAdapterRegistry from zope.interface._compat import _normalize_name -from zope.interface._compat import STRING_TYPES from zope.interface._compat import _use_c_impl __all__ = @@ -62,7 +61,7 @@ # ``tuple(map(lambda t: t, range(10)))`` -> 168ns # -class BaseAdapterRegistry(object): +class BaseAdapterRegistry: """ A basic implementation of the data storage and algorithms required for a :class:`zope.interface.interfaces.IAdapterRegistry`. @@ -262,7 +261,7 @@ self._v_lookup.changed(originally_changed) def register(self, required, provided, name, value): - if not isinstance(name, STRING_TYPES): + if not isinstance(name, str): raise ValueError('name is not a string') if value is None: self.unregister(required, provided, name, value) @@ -318,7 +317,7 @@ return components.get(name) - def registered(self, required, provided, name=u''): + def registered(self, required, provided, name=''): return self._find_leaf( self._adapters, required, @@ -334,8 +333,7 @@ else: for k, v in components.items(): new_parent_k = parent_k + (k,) - for x, y in cls._allKeys(v, i - 1, new_parent_k): - yield x, y + yield from cls._allKeys(v, i - 1, new_parent_k) def _all_entries(self, byorder): # Recurse through the mapping levels of the `byorder` sequence, @@ -366,8 +364,7 @@ .. versionadded:: 5.3.0 """ - for t in self._all_entries(self._adapters): - yield t + yield from self._all_entries(self._adapters) def unregister(self, required, provided, name, value=None): required = tuple(_convert_None_to_Interface(r) for r in required) @@ -419,7 +416,7 @@ def subscribe(self, required, provided, value): required = tuple(_convert_None_to_Interface(r) for r in required) - name = u'' + name = '' order = len(required) byorder = self._subscribers while len(byorder) <= order: @@ -449,7 +446,7 @@ self._subscribers, required, provided, - u'' + '' ) or () return subscriber if subscriber in subscribers else None @@ -486,7 +483,7 @@ lookups.append((components, k)) components = d - old = components.get(u'') + old = components.get('') if not old: # this is belt-and-suspenders against the failure of cleanup below return # pragma: no cover @@ -509,7 +506,7 @@ return if new: - componentsu'' = new + components'' = new else: # Instead of setting componentsu'' = new, we clean out # empty containers, since we don't want our keys to @@ -517,7 +514,7 @@ # is often a problem when an interface is slated for # removal; a hold-over entry in the registry can make it # difficult to remove such interfaces. - del componentsu'' + del components'' for comp, k in reversed(lookups): d = compk if d: @@ -601,7 +598,7 @@ _not_in_mapping = object() @_use_c_impl -class LookupBase(object): +class LookupBase: def __init__(self): self._cache = {} @@ -626,8 +623,8 @@ cache = c return cache - def lookup(self, required, provided, name=u'', default=None): - if not isinstance(name, STRING_TYPES): + def lookup(self, required, provided, name='', default=None): + if not isinstance(name, str): raise ValueError('name is not a string') cache = self._getcache(provided, name) required = tuple(required) @@ -648,8 +645,8 @@ return result - def lookup1(self, required, provided, name=u'', default=None): - if not isinstance(name, STRING_TYPES): + def lookup1(self, required, provided, name='', default=None): + if not isinstance(name, str): raise ValueError('name is not a string') cache = self._getcache(provided, name) result = cache.get(required, _not_in_mapping) @@ -661,11 +658,11 @@ return result - def queryAdapter(self, object, provided, name=u'', default=None): + def queryAdapter(self, object, provided, name='', default=None): return self.adapter_hook(provided, object, name, default) - def adapter_hook(self, provided, object, name=u'', default=None): - if not isinstance(name, STRING_TYPES): + def adapter_hook(self, provided, object, name='', default=None): + if not isinstance(name, str): raise ValueError('name is not a string') required = providedBy(object) cache = self._getcache(provided, name) @@ -742,16 +739,16 @@ return LookupBaseFallback.subscriptions(self, required, provided) -class AdapterLookupBase(object): +class AdapterLookupBase: def __init__(self, registry): self._registry = registry self._required = {} self.init_extendors() - super(AdapterLookupBase, self).__init__() + super().__init__() def changed(self, ignored=None): - super(AdapterLookupBase, self).changed(None) + super().changed(None) for r in self._required.keys(): r = r() if r is not None: @@ -813,7 +810,7 @@ r.subscribe(self) _refsref = 1 - def _uncached_lookup(self, required, provided, name=u''): + def _uncached_lookup(self, required, provided, name=''): required = tuple(required) result = None order = len(required) @@ -836,7 +833,7 @@ return result - def queryMultiAdapter(self, objects, provided, name=u'', default=None): + def queryMultiAdapter(self, objects, provided, name='', default=None): factory = self.lookup(providedBy(o) for o in objects, provided, name) if factory is None: return default @@ -884,7 +881,7 @@ if extendors is None: continue - _subscriptions(byorderorder, required, extendors, u'', + _subscriptions(byorderorder, required, extendors, '', result, 0, order) self._subscribe(*required) @@ -922,7 +919,7 @@ # we need to keep track of our invalidating subregistries. self._v_subregistries = weakref.WeakKeyDictionary() - super(AdapterRegistry, self).__init__(bases) + super().__init__(bases) def _addSubregistry(self, r): self._v_subregistriesr = 1 @@ -940,10 +937,10 @@ if r not in old: r._addSubregistry(self) - super(AdapterRegistry, self)._setBases(bases) + super()._setBases(bases) def changed(self, originally_changed): - super(AdapterRegistry, self).changed(originally_changed) + super().changed(originally_changed) for sub in self._v_subregistries.keys(): sub.changed(originally_changed)
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/advice.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/advice.py
Changed
@@ -26,15 +26,8 @@ """ from types import FunctionType -try: - from types import ClassType -except ImportError: - __python3 = True -else: - __python3 = False __all__ = - 'addClassAdvisor', 'determineMetaclass', 'getFrameInfo', 'isClassAdvisor', @@ -79,86 +72,6 @@ return kind, module, f_locals, f_globals -def addClassAdvisor(callback, depth=2): - """Set up 'callback' to be passed the containing class upon creation - - This function is designed to be called by an "advising" function executed - in a class suite. The "advising" function supplies a callback that it - wishes to have executed when the containing class is created. The - callback will be given one argument: the newly created containing class. - The return value of the callback will be used in place of the class, so - the callback should return the input if it does not wish to replace the - class. - - The optional 'depth' argument to this function determines the number of - frames between this function and the targeted class suite. 'depth' - defaults to 2, since this skips this function's frame and one calling - function frame. If you use this function from a function called directly - in the class suite, the default will be correct, otherwise you will need - to determine the correct depth yourself. - - This function works by installing a special class factory function in - place of the '__metaclass__' of the containing class. Therefore, only - callbacks *after* the last '__metaclass__' assignment in the containing - class will be executed. Be sure that classes using "advising" functions - declare any '__metaclass__' *first*, to ensure all callbacks are run.""" - # This entire approach is invalid under Py3K. Don't even try to fix - # the coverage for this block there. :( - if __python3: # pragma: no cover - raise TypeError('Class advice impossible in Python3') - - frame = sys._getframe(depth) - kind, module, caller_locals, caller_globals = getFrameInfo(frame) - - # This causes a problem when zope interfaces are used from doctest. - # In these cases, kind == "exec". - # - #if kind != "class": - # raise SyntaxError( - # "Advice must be in the body of a class statement" - # ) - - previousMetaclass = caller_locals.get('__metaclass__') - if __python3: # pragma: no cover - defaultMetaclass = caller_globals.get('__metaclass__', type) - else: - defaultMetaclass = caller_globals.get('__metaclass__', ClassType) - - - def advise(name, bases, cdict): - - if '__metaclass__' in cdict: - del cdict'__metaclass__' - - if previousMetaclass is None: - if bases: - # find best metaclass or use global __metaclass__ if no bases - meta = determineMetaclass(bases) - else: - meta = defaultMetaclass - - elif isClassAdvisor(previousMetaclass): - # special case: we can't compute the "true" metaclass here, - # so we need to invoke the previous metaclass and let it - # figure it out for us (and apply its own advice in the process) - meta = previousMetaclass - - else: - meta = determineMetaclass(bases, previousMetaclass) - - newClass = meta(name,bases,cdict) - - # this lets the callback replace the class completely, if it wants to - return callback(newClass) - - # introspection data only, not used by inner function - advise.previousMetaclass = previousMetaclass - advise.callback = callback - - # install the advisor - caller_locals'__metaclass__' = advise - - def isClassAdvisor(ob): """True if 'ob' is a class advisor function""" return isinstance(ob,FunctionType) and hasattr(ob,'previousMetaclass') @@ -180,14 +93,9 @@ candidates = minimalBases(meta) # minimal set of metaclasses - if not candidates: # pragma: no cover - # they're all "classic" classes - assert(not __python3) # This should not happen under Python 3 - return ClassType - - elif len(candidates)>1: + if len(candidates)>1: # We could auto-combine, but for now we won't... - raise TypeError("Incompatible metatypes",bases) + raise TypeError("Incompatible metatypes", bases) # Just one, return it return candidates0 @@ -195,9 +103,6 @@ def minimalBases(classes): """Reduce a list of base classes to its ordered minimum equivalent""" - - if not __python3: # pragma: no cover - classes = c for c in classes if c is not ClassType candidates = for m in classes:
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/common/__init__.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/common/__init__.py
Changed
@@ -28,7 +28,7 @@ # pylint:disable=no-self-argument,no-method-argument # pylint:disable=unexpected-special-method-signature -class optional(object): +class optional: # Apply this decorator to a method definition to make it # optional (remove it from the list of required names), overriding # the definition inherited from the ABC. @@ -162,7 +162,7 @@ return '' docs = "\n\nThe following methods are optional:\n - " + "\n-".join( - "%s\n%s" % (k, v.__doc__) for k, v in optionals.items() + "{}\n{}".format(k, v.__doc__) for k, v in optionals.items() ) return docs @@ -175,7 +175,7 @@ return "`%s`" % name if mod == '_io': mod = 'io' - return "`%s.%s`" % (mod, name) + return "`{}.{}`".format(mod, name) implementations_doc = "\n - ".join( ref(c) for c in sorted(self.getRegisteredConformers(), key=ref) @@ -187,7 +187,7 @@ based_on_doc = based_on_doc.splitlines() based_on_doc = based_on_doc0 if based_on_doc else '' - doc = """Interface for the ABC `%s.%s`.\n\n%s%s%s""" % ( + doc = """Interface for the ABC `{}.{}`.\n\n{}{}{}""".format( based_on.__module__, based_on.__name__, attrs.get('__doc__', based_on_doc), self.__optional_methods_to_docs(attrs),
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/common/builtins.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/common/builtins.py
Changed
@@ -17,7 +17,6 @@ .. versionadded:: 5.0.0 """ -from __future__ import absolute_import from zope.interface import classImplements @@ -60,12 +59,11 @@ class ITextString(collections.ISequence): """ - Interface for text (unicode) strings. + Interface for text ("unicode") strings. - On Python 2, this is :class:`unicode`. On Python 3, - this is :class:`str` + This is :class:`str` """ - extra_classes = (type(u'unicode'),) + extra_classes = (str,) class IByteString(collections.IByteString): @@ -81,12 +79,11 @@ extra_classes = (bytes,) -class INativeString(IByteString if str is bytes else ITextString): +class INativeString(ITextString): """ Interface for native strings. - On all Python versions, this is :class:`str`. On Python 2, - this extends :class:`IByteString`, while on Python 3 it extends + On all Python versions, this is :class:`str`. Tt extends :class:`ITextString`. """ # We're not extending ABCInterface so extra_classes won't work @@ -119,7 +116,4 @@ many different classes that implement different interfaces from :mod:`zope.interface.common.io`. """ - try: - extra_classes = (file,) - except NameError: - extra_classes = () + extra_classes = ()
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/common/collections.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/common/collections.py
Changed
@@ -29,37 +29,16 @@ .. versionadded:: 5.0.0 """ -from __future__ import absolute_import import sys from abc import ABCMeta -# The collections imports are here, and not in -# zope.interface._compat to avoid importing collections -# unless requested. It's a big import. -try: - from collections import abc -except ImportError: - import collections as abc +from collections import abc from collections import OrderedDict -try: - # On Python 3, all of these extend the appropriate collection ABC, - # but on Python 2, UserDict does not (though it is registered as a - # MutableMapping). (Importantly, UserDict on Python 2 is *not* - # registered, because it's not iterable.) Extending the ABC is not - # taken into account for interface declarations, though, so we - # need to be explicit about it. - from collections import UserList - from collections import UserDict - from collections import UserString -except ImportError: - # Python 2 - from UserList import UserList - from UserDict import IterableUserDict as UserDict - from UserString import UserString - -from zope.interface._compat import PYTHON2 as PY2 -from zope.interface._compat import PYTHON3 as PY3 +from collections import UserList +from collections import UserDict +from collections import UserString + from zope.interface.common import ABCInterface from zope.interface.common import optional @@ -68,8 +47,6 @@ # pylint:disable=unexpected-special-method-signature # pylint:disable=no-value-for-parameter -PY35 = sys.version_info:2 >= (3, 5) -PY36 = sys.version_info:2 >= (3, 6) def _new_in_ver(name, ver, bases_if_missing=(ABCMeta,), @@ -144,7 +121,7 @@ abc = abc.Iterator class IReversible(IIterable): - abc = _new_in_ver('Reversible', PY36, (IIterable.getABC(),)) + abc = _new_in_ver('Reversible', True, (IIterable.getABC(),)) @optional def __reversed__(): @@ -155,8 +132,8 @@ """ class IGenerator(IIterator): - # New in 3.5 - abc = _new_in_ver('Generator', PY35, (IIterator.getABC(),)) + # New in Python 3.5 + abc = _new_in_ver('Generator', True, (IIterator.getABC(),)) class ISized(ABCInterface): @@ -168,7 +145,7 @@ class ICollection(ISized, IIterable, IContainer): - abc = _new_in_ver('Collection', PY36, + abc = _new_in_ver('Collection', True, (ISized.getABC(), IIterable.getABC(), IContainer.getABC())) @@ -205,7 +182,7 @@ """ This unifies `bytes` and `bytearray`. """ - abc = _new_in_ver('ByteString', PY3, + abc = _new_in_ver('ByteString', True, (ISequence.getABC(),), (bytes, bytearray)) @@ -226,14 +203,6 @@ # produces an inconsistent IRO if we also try to register it # here. ignored_classes = (OrderedDict,) - if PY2: - @optional - def __eq__(other): - """ - The interpreter will supply one. - """ - - __ne__ = __eq__ class IMutableMapping(IMapping): @@ -265,20 +234,20 @@ """ class IAwaitable(ABCInterface): - abc = _new_in_ver('Awaitable', PY35) + abc = _new_in_ver('Awaitable', True) class ICoroutine(IAwaitable): - abc = _new_in_ver('Coroutine', PY35) + abc = _new_in_ver('Coroutine', True) class IAsyncIterable(ABCInterface): - abc = _new_in_ver('AsyncIterable', PY35) + abc = _new_in_ver('AsyncIterable', True) class IAsyncIterator(IAsyncIterable): - abc = _new_in_ver('AsyncIterator', PY35) + abc = _new_in_ver('AsyncIterator', True) class IAsyncGenerator(IAsyncIterator): - abc = _new_in_ver('AsyncGenerator', PY36) + abc = _new_in_ver('AsyncGenerator', True)
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/common/interfaces.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/common/interfaces.py
Changed
@@ -22,11 +22,7 @@ class IStandardError(IException): - "Interface for `StandardError` (Python 2 only.)" -try: - classImplements(StandardError, IStandardError) -except NameError: #pragma NO COVER - pass # StandardError does not exist in Python 3 + "Interface for `StandardError` (no longer existing.)" class IWarning(IException):
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/common/io.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/common/io.py
Changed
@@ -18,7 +18,6 @@ .. versionadded:: 5.0.0 """ -from __future__ import absolute_import import io as abc @@ -37,16 +36,7 @@ class IBufferedIOBase(IIOBase): abc = abc.BufferedIOBase - try: - import cStringIO - except ImportError: - # Python 3 - extra_classes = () - else: - import StringIO - extra_classes = (StringIO.StringIO, cStringIO.InputType, cStringIO.OutputType) - del cStringIO - del StringIO + extra_classes = () class ITextIOBase(IIOBase):
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/common/mapping.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/common/mapping.py
Changed
@@ -29,7 +29,6 @@ interfaces in this module. """ from zope.interface import Interface -from zope.interface._compat import PYTHON2 as PY2 from zope.interface.common import collections class IItemMapping(Interface): @@ -103,20 +102,8 @@ """A mapping that has distinct methods for iterating without copying. - On Python 2, a `dict` has these methods, but on Python 3 - the methods defined in `IEnumerableMapping` already iterate - without copying. """ - if PY2: - def iterkeys(): - "iterate over keys; equivalent to ``__iter__``" - - def itervalues(): - "iterate over values" - - def iteritems(): - "iterate over items" class IClonableMapping(Interface): """Something that can produce a copy of itself. @@ -131,13 +118,10 @@ """ Something with a particular method equivalent to ``__contains__``. - On Python 2, `dict` provides this method, but it was removed + On Python 2, `dict` provided the ``has_key`` method, but it was removed in Python 3. """ - if PY2: - def has_key(key): - """Tell if a key exists in the mapping; equivalent to ``__contains__``""" class IExtendedWriteMapping(IWriteMapping): """Additional mutation methods.
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/common/numbers.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/common/numbers.py
Changed
@@ -18,14 +18,12 @@ .. versionadded:: 5.0.0 """ -from __future__ import absolute_import import numbers as abc from zope.interface.common import ABCInterface from zope.interface.common import optional -from zope.interface._compat import PYTHON2 as PY2 # pylint:disable=inherit-non-class, # pylint:disable=no-self-argument,no-method-argument @@ -46,14 +44,6 @@ Rarely implemented, even in builtin types. """ - if PY2: - @optional - def __eq__(other): - """ - The interpreter may supply one through complicated rules. - """ - - __ne__ = __eq__ class IReal(IComplex): abc = abc.Real @@ -66,15 +56,6 @@ __floor__ = __ceil__ = __complex__ - if PY2: - @optional - def __le__(other): - """ - The interpreter may supply one through complicated rules. - """ - - __lt__ = __le__ - class IRational(IReal): abc = abc.Rational
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/common/sequence.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/common/sequence.py
Changed
@@ -32,7 +32,6 @@ __docformat__ = 'restructuredtext' from zope.interface import Interface from zope.interface.common import collections -from zope.interface._compat import PYTHON2 as PY2 class IMinimalSequence(collections.IIterable): """Most basic sequence interface. @@ -107,14 +106,6 @@ def __rmul__(n): """``x.__rmul__(n) <==> n * x``""" - if PY2: - def __getslice__(i, j): - """``x.__getslice__(i, j) <==> xi:j`` - - Use of negative indices is not supported. - - Deprecated since Python 2.0 but still a part of `UserList`. - """ class IExtendedReadSequence(IReadSequence): """Full read interface for lists""" @@ -145,23 +136,6 @@ supports slice objects. """ - if PY2: - def __setslice__(i, j, other): - """``x.__setslice__(i, j, other) <==> xi:j = other`` - - Use of negative indices is not supported. - - Deprecated since Python 2.0 but still a part of `UserList`. - """ - - def __delslice__(i, j): - """``x.__delslice__(i, j) <==> del xi:j`` - - Use of negative indices is not supported. - - Deprecated since Python 2.0 but still a part of `UserList`. - """ - def __iadd__(y): """``x.__iadd__(y) <==> x += y``"""
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/common/tests/__init__.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/common/tests/__init__.py
Changed
@@ -60,7 +60,7 @@ self.assertTrue(self.verify(iface, stdlib_class)) - suffix = "%s_%s_%s_%s" % ( + suffix = "{}_{}_{}_{}".format( stdlib_class.__module__.replace('.', '_'), stdlib_class.__name__, iface.__module__.replace('.', '_'),
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/common/tests/basemapping.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/common/tests/basemapping.py
Changed
@@ -63,7 +63,7 @@ test___len__(self, inst, state) -class BaseTestIReadMapping(object): +class BaseTestIReadMapping: def testIReadMapping(self): inst = self._IReadMapping__sample() state = self._IReadMapping__stateDict()
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/common/tests/test_builtins.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/common/tests/test_builtins.py
Changed
@@ -9,11 +9,9 @@ # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. ############################################################################## -from __future__ import absolute_import import unittest -from zope.interface._compat import PYTHON2 as PY2 from zope.interface.common import builtins from . import VerifyClassMixin @@ -29,12 +27,12 @@ add_verify_tests(TestVerifyClass, ( (builtins.IList, (list,)), (builtins.ITuple, (tuple,)), - (builtins.ITextString, (type(u'abc'),)), + (builtins.ITextString, (str,)), (builtins.IByteString, (bytes,)), (builtins.INativeString, (str,)), (builtins.IBool, (bool,)), (builtins.IDict, (dict,)), - (builtins.IFile, (file,) if PY2 else ()), + (builtins.IFile, ()), ))
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/common/tests/test_collections.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/common/tests/test_collections.py
Changed
@@ -13,18 +13,12 @@ import array import unittest -try: - import collections.abc as abc -except ImportError: - import collections as abc +from collections import abc from collections import deque from collections import OrderedDict -try: - from types import MappingProxyType -except ImportError: - MappingProxyType = object() +from types import MappingProxyType from zope.interface import Invalid @@ -34,7 +28,7 @@ from zope.interface._compat import PYPY -from zope.interface._compat import PYTHON2 as PY2 + from . import add_abc_interface_tests from . import VerifyClassMixin @@ -65,16 +59,6 @@ self.assertTrue(self.verify(collections.ISequence, collections.UserString)) - def test_non_iterable_UserDict(self): - try: - from UserDict import UserDict as NonIterableUserDict # pylint:disable=import-error - except ImportError: - # Python 3 - self.skipTest("No UserDict.NonIterableUserDict on Python 3") - - with self.assertRaises(Invalid): - self.verify(collections.IMutableMapping, NonIterableUserDict) - # Now we go through the registry, which should have several things, # mostly builtins, but if we've imported other libraries already, # it could contain things from outside of there too. We aren't concerned @@ -110,30 +94,13 @@ # Likewise for index range, }) - if PY2: - # pylint:disable=undefined-variable,no-member - # There are a lot more types that are fundamentally unverifiable on Python 2. - UNVERIFIABLE.update({ - # Missing several key methods like __getitem__ - basestring, - # Missing __iter__ and __contains__, hard to construct. - buffer, - # Missing ``__contains__``, ``count`` and ``index``. - xrange, - # These two are missing Set.isdisjoint() - type({}.viewitems()), - type({}.viewkeys()), - }) - NON_STRICT_RO = { - } - else: - UNVERIFIABLE_RO = { - # ``array.array`` fails the ``test_auto_ro_*`` tests with and - # without strict RO but only on Windows (AppVeyor) on Python 3.10.0 - # (in older versions ``array.array`` does not appear as - # ``IMutableSequence``). - array.array, - } + UNVERIFIABLE_RO = { + # ``array.array`` fails the ``test_auto_ro_*`` tests with and + # without strict RO but only on Windows (AppVeyor) on Python 3.10.0 + # (in older versions ``array.array`` does not appear as + # ``IMutableSequence``). + array.array, + } add_abc_interface_tests(TestVerifyClass, collections.ISet.__module__) @@ -154,7 +121,7 @@ type(iter({}.keys())): lambda: iter({}.keys()), type(iter({}.items())): lambda: iter({}.items()), type(iter({}.values())): lambda: iter({}.values()), - type((i for i in range(1))): lambda: (i for i in range(3)), + type(i for i in range(1)): lambda: (i for i in range(3)), type(iter()): lambda: iter(), type(reversed()): lambda: reversed(), 'longrange_iterator': unittest.SkipTest, @@ -166,16 +133,10 @@ type(iter(tuple())): lambda: iter(tuple()), } - if PY2: - # pylint:disable=undefined-variable,no-member - CONSTRUCTORS.update({ - collections.IValuesView: {}.viewvalues, - }) - else: - UNVERIFIABLE_RO = { - # ``array.array`` fails the ``test_auto_ro_*`` tests with and - # without strict RO but only on Windows (AppVeyor) on Python 3.10.0 - # (in older versions ``array.array`` does not appear as - # ``IMutableSequence``). - array.array, - } + UNVERIFIABLE_RO = { + # ``array.array`` fails the ``test_auto_ro_*`` tests with and + # without strict RO but only on Windows (AppVeyor) on Python 3.10.0 + # (in older versions ``array.array`` does not appear as + # ``IMutableSequence``). + array.array, + }
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/common/tests/test_io.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/common/tests/test_io.py
Changed
@@ -40,13 +40,3 @@ abc.FileIO: lambda: abc.FileIO(__file__), '_WindowsConsoleIO': unittest.SkipTest, } - - try: - import cStringIO - except ImportError: - pass - else: - CONSTRUCTORS.update({ - cStringIO.InputType: lambda cStringIO=cStringIO: cStringIO.StringIO('abc'), - cStringIO.OutputType: cStringIO.StringIO, - })
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/declarations.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/declarations.py
Changed
@@ -32,14 +32,11 @@ from types import ModuleType import weakref -from zope.interface.advice import addClassAdvisor from zope.interface.interface import Interface from zope.interface.interface import InterfaceClass from zope.interface.interface import SpecificationBase from zope.interface.interface import Specification from zope.interface.interface import NameAndModuleComparisonMixin -from zope.interface._compat import CLASS_TYPES as DescriptorAwareMetaClasses -from zope.interface._compat import PYTHON3 from zope.interface._compat import _use_c_impl __all__ = @@ -52,11 +49,6 @@ # Registry of class-implementation specifications BuiltinImplementationSpecifications = {} -_ADVICE_ERROR = ('Class advice impossible in Python3. ' - 'Use the @%s class decorator instead.') - -_ADVICE_WARNING = ('The %s API is deprecated, and will not work in Python3 ' - 'Use the @%s class decorator instead.') def _next_super_class(ob): # When ``ob`` is an instance of ``super``, return @@ -68,7 +60,7 @@ next_class = complete_mrocomplete_mro.index(class_that_invoked_super) + 1 return next_class -class named(object): +class named: def __init__(self, name): self.name = name @@ -263,9 +255,9 @@ @property def _v_attrs(self): - # _v_attrs is not a public, documented property, but some client - # code uses it anyway as a convenient place to cache things. To keep - # the empty declaration truly immutable, we must ignore that. That includes + # _v_attrs is not a public, documented property, but some client code + # uses it anyway as a convenient place to cache things. To keep the + # empty declaration truly immutable, we must ignore that. That includes # ignoring assignments as well. return {} @@ -335,7 +327,7 @@ del self._super_cache except AttributeError: pass - return super(Implements, self).changed(originally_changed) + return super().changed(originally_changed) def __repr__(self): if self.inherit: @@ -345,7 +337,7 @@ declared_names = self._argument_names_for_repr(self.declared) if declared_names: declared_names = ', ' + declared_names - return 'classImplements(%s%s)' % (name, declared_names) + return 'classImplements({}{})'.format(name, declared_names) def __reduce__(self): return implementedBy, (self.inherit, ) @@ -486,8 +478,7 @@ if not hasattr(cls, '__providedBy__'): cls.__providedBy__ = objectSpecificationDescriptor - if (isinstance(cls, DescriptorAwareMetaClasses) - and '__provides__' not in cls.__dict__): + if isinstance(cls, type) and '__provides__' not in cls.__dict__: # Make sure we get a __provides__ descriptor cls.__provides__ = ClassProvides( cls, @@ -631,7 +622,7 @@ return cls -class implementer(object): +class implementer: """ Declare the interfaces implemented by instances of a class. @@ -670,9 +661,8 @@ self.interfaces = interfaces def __call__(self, ob): - if isinstance(ob, DescriptorAwareMetaClasses): - # This is the common branch for new-style (object) and - # on Python 2 old-style classes. + if isinstance(ob, type): + # This is the common branch for classes. classImplements(ob, *self.interfaces) return ob @@ -684,7 +674,7 @@ raise TypeError("Can't declare implements", ob) return ob -class implementer_only(object): +class implementer_only: """Declare the only interfaces implemented by instances of a class This function is called as a class decorator. @@ -723,88 +713,6 @@ classImplementsOnly(ob, *self.interfaces) return ob -def _implements(name, interfaces, do_classImplements): - # This entire approach is invalid under Py3K. Don't even try to fix - # the coverage for this block there. :( - frame = sys._getframe(2) # pylint:disable=protected-access - locals = frame.f_locals # pylint:disable=redefined-builtin - - # Try to make sure we were called from a class def. In 2.2.0 we can't - # check for __module__ since it doesn't seem to be added to the locals - # until later on. - if locals is frame.f_globals or '__module__' not in locals: - raise TypeError(name+" can be used only from a class definition.") - - if '__implements_advice_data__' in locals: - raise TypeError(name+" can be used only once in a class definition.") - - locals'__implements_advice_data__' = interfaces, do_classImplements - addClassAdvisor(_implements_advice, depth=3) - -def implements(*interfaces): - """ - Declare interfaces implemented by instances of a class. - - .. deprecated:: 5.0 - This only works for Python 2. The `implementer` decorator - is preferred for all versions. - - This function is called in a class definition. - - The arguments are one or more interfaces or interface - specifications (`~zope.interface.interfaces.IDeclaration` - objects). - - The interfaces given (including the interfaces in the - specifications) are added to any interfaces previously declared. - - Previous declarations include declarations for base classes unless - `implementsOnly` was used. - - This function is provided for convenience. It provides a more - convenient way to call `classImplements`. For example:: - - implements(I1) - - is equivalent to calling:: - - classImplements(C, I1) - - after the class has been created. - """ - # This entire approach is invalid under Py3K. Don't even try to fix - # the coverage for this block there. :( - if PYTHON3: - raise TypeError(_ADVICE_ERROR % 'implementer') - _implements("implements", interfaces, classImplements) - -def implementsOnly(*interfaces): - """Declare the only interfaces implemented by instances of a class - - This function is called in a class definition. - - The arguments are one or more interfaces or interface - specifications (`~zope.interface.interfaces.IDeclaration` objects). - - Previous declarations including declarations for base classes - are overridden. - - This function is provided for convenience. It provides a more - convenient way to call `classImplementsOnly`. For example:: - - implementsOnly(I1) - - is equivalent to calling:: - - classImplementsOnly(I1) - - after the class has been created. - """ - # This entire approach is invalid under Py3K. Don't even try to fix - # the coverage for this block there. :( - if PYTHON3: - raise TypeError(_ADVICE_ERROR % 'implementer_only') - _implements("implementsOnly", interfaces, classImplementsOnly) ############################################################################## # @@ -849,9 +757,9 @@ if len(mod_names) == 1: mod_names = "sys.modules%r" % mod_names0 ordered_names = ( - '%s, ' % (mod_names,) + '{}, '.format(mod_names) ) + ordered_names - return "%s(%s)" % ( + return "{}({})".format( function_name, ordered_names, ) @@ -908,10 +816,9 @@ cls = getattr(object, '__class__', None) if cls is not None and getattr(cls, '__class__', None) is cls: # It's a meta class (well, at least it it could be an extension class) - # Note that we can't get here from Py3k tests: there is no normal + # Note that we can't get here from the tests: there is no normal # class which isn't descriptor aware. - if not isinstance(object, - DescriptorAwareMetaClasses): + if not isinstance(object, type): raise TypeError("Attempt to make an interface declaration on a " "non-descriptor-aware class") @@ -919,12 +826,7 @@ if cls is None: cls = type(object) - issub = False - for damc in DescriptorAwareMetaClasses: - if issubclass(cls, damc): - issub = True - break - if issub: + if issubclass(cls, type): # we have a class or type. We'll use a special descriptor # that provides some extra caching object.__provides__ = ClassProvides(object, cls, *interfaces) @@ -1011,7 +913,7 @@ # Thus, as our repr, we go with the ``directlyProvides()`` syntax. interfaces = (self._cls, ) + self.__args2: ordered_names = self._argument_names_for_repr(interfaces) - return "directlyProvides(%s)" % (ordered_names,) + return "directlyProvides({})".format(ordered_names) def __reduce__(self): return self.__class__, self.__args @@ -1039,7 +941,7 @@ return Declaration(provides.__bases__:-1) -def classProvides(*interfaces): +class provider: """Declare interfaces provided directly by a class This function is called in a class definition. @@ -1059,47 +961,16 @@ This function is provided for convenience. It provides a more convenient way to call `directlyProvides` for a class. For example:: - classProvides(I1) + @provider(I1) + class C: + pass is equivalent to calling:: - directlyProvides(theclass, I1) + directlyProvides(C, I1) after the class has been created. """ - # This entire approach is invalid under Py3K. Don't even try to fix - # the coverage for this block there. :( - - if PYTHON3: - raise TypeError(_ADVICE_ERROR % 'provider') - - frame = sys._getframe(1) # pylint:disable=protected-access - locals = frame.f_locals # pylint:disable=redefined-builtin - - # Try to make sure we were called from a class def - if (locals is frame.f_globals) or ('__module__' not in locals): - raise TypeError("classProvides can be used only from a " - "class definition.") - - if '__provides__' in locals: - raise TypeError( - "classProvides can only be used once in a class definition.") - - locals"__provides__" = _normalizeargs(interfaces) - - addClassAdvisor(_classProvides_advice, depth=2) - -def _classProvides_advice(cls): - # This entire approach is invalid under Py3K. Don't even try to fix - # the coverage for this block there. :( - interfaces = cls.__dict__'__provides__' - del cls.__provides__ - directlyProvides(cls, *interfaces) - return cls - - -class provider(object): - """Class decorator version of classProvides""" def __init__(self, *interfaces): self.interfaces = interfaces @@ -1257,7 +1128,7 @@ @_use_c_impl -class ObjectSpecificationDescriptor(object): +class ObjectSpecificationDescriptor: """Implement the ``__providedBy__`` attribute The ``__providedBy__`` attribute computes the interfaces provided by
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/document.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/document.py
Changed
@@ -32,7 +32,7 @@ """ if rst: - inline_literal = lambda s: "``%s``" % (s,) + inline_literal = lambda s: "``{}``".format(s) else: inline_literal = lambda s: s @@ -61,7 +61,7 @@ level += 1 for name, desc in namesAndDescriptions: if not hasattr(desc, 'getSignatureString'): # ugh... - item = "%s -- %s" % (inline_literal(desc.getName()), + item = "{} -- {}".format(inline_literal(desc.getName()), desc.getDoc() or 'no documentation') outp(_justify_and_indent(_trim_doc_string(item), level, munge)) level -= 1 @@ -70,8 +70,8 @@ level += 1 for name, desc in namesAndDescriptions: if hasattr(desc, 'getSignatureString'): # ugh... - _call = "%s%s" % (desc.getName(), desc.getSignatureString()) - item = "%s -- %s" % (inline_literal(_call), + _call = "{}{}".format(desc.getName(), desc.getSignatureString()) + item = "{} -- {}".format(inline_literal(_call), desc.getDoc() or 'no documentation') outp(_justify_and_indent(_trim_doc_string(item), level, munge))
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/exceptions.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/exceptions.py
Changed
@@ -92,7 +92,7 @@ target = self.target if target is self._NOT_GIVEN: return "An object" - return "The object %r" % (target,) + return "The object {!r}".format(target) @property def _str_description(self): @@ -105,7 +105,7 @@ _str_trailer = '.' def __str__(self): - return "%s %s%s%s%s" % ( + return "{} {}{}{}{}".format( self._str_subject, self._str_description, self._str_conjunction, @@ -224,7 +224,7 @@ message = message.replace("implementation", '%r') message = message % (self.__implementation_str(impl),) - return 'The contract of %s is violated because %s' % ( + return 'The contract of {} is violated because {}'.format( repr(self.method) if isinstance(self.method, str) else self.method, message, ) @@ -244,7 +244,7 @@ _NOT_GIVEN_CATCH = () def __init__(self, interface, target, exceptions): - super(MultipleInvalid, self).__init__(interface, target, tuple(exceptions)) + super().__init__(interface, target, tuple(exceptions)) @property def exceptions(self):
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/interface.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/interface.py
Changed
@@ -20,7 +20,6 @@ import weakref from zope.interface._compat import _use_c_impl -from zope.interface._compat import PYTHON2 as PY2 from zope.interface.exceptions import Invalid from zope.interface.ro import ro as calculate_ro from zope.interface import ro @@ -63,7 +62,7 @@ return _decorator_non_return -class Element(object): +class Element: """ Default implementation of `zope.interface.interfaces.IElement`. """ @@ -128,7 +127,7 @@ @_use_c_impl -class SpecificationBase(object): +class SpecificationBase: # This object is the base of the inheritance hierarchy for ClassProvides: # # ClassProvides < ClassProvidesBase, Declaration @@ -174,7 +173,7 @@ __call__ = isOrExtends -class NameAndModuleComparisonMixin(object): +class NameAndModuleComparisonMixin: # Internal use. Implement the basic sorting operators (but not (in)equality # or hashing). Subclasses must provide ``__name__`` and ``__module__`` # attributes. Subclasses will be mutually comparable; but because equality @@ -648,7 +647,7 @@ return cls.__module def __repr__(cls): - return "<class '%s.%s'>" % ( + return "<class '{}.{}'>".format( cls.__module, cls.__name__, ) @@ -720,27 +719,6 @@ cls_bases, needs_custom_class ) - elif PY2 and bases and len(bases) > 1: - bases_with_custom_methods = tuple( - type(b) - for b in bases - if issubclass(type(b), _InterfaceClassWithCustomMethods) - ) - - # If we have a subclass of InterfaceClass in *bases*, - # Python 3 is smart enough to pass that as *cls*, but Python - # 2 just passes whatever the first base in *bases* is. This means that if - # we have multiple inheritance, and one of our bases has already defined - # a custom method like ``__adapt__``, we do the right thing automatically - # and extend it on Python 3, but not necessarily on Python 2. To fix this, we need - # to run the MRO algorithm and get the most derived base manually. - # Note that this only works for consistent resolution orders - if bases_with_custom_methods: - cls = type( # pylint:disable=self-cls-assignment - name + "<WithCustomMethods>", - bases_with_custom_methods, - {} - ).__mro__1 # Not the class we created, the most derived. return _InterfaceClassBase.__new__(cls) @@ -793,7 +771,7 @@ Specification.__init__(self, bases) self.__attrs = self.__compute_attrs(attrs) - self.__identifier__ = "%s.%s" % (__module__, name) + self.__identifier__ = "{}.{}".format(__module__, name) def __compute_attrs(self, attrs): # Make sure that all recorded attributes (and methods) are of type @@ -930,7 +908,7 @@ return self._v_repr except AttributeError: name = str(self) - r = "<%s %s>" % (self.__class__.__name__, name) + r = "<{} {}>".format(self.__class__.__name__, name) self._v_repr = r # pylint:disable=attribute-defined-outside-init return r @@ -938,7 +916,7 @@ name = self.__name__ m = self.__ibmodule__ if m: - name = '%s.%s' % (m, name) + name = '{}.{}'.format(m, name) return name def _call_conform(self, conform): @@ -1000,7 +978,7 @@ return of + (self.__name__ or '<unknown>') + self._get_str_info() def __repr__(self): - return "<%s.%s object at 0x%x %s>" % ( + return "<{}.{} object at 0x{:x} {}>".format( type(self).__module__, type(self).__name__, id(self),
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/interfaces.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/interfaces.py
Changed
@@ -754,122 +754,9 @@ .. seealso:: `zope.interface.noLongerProvides` """ - def implements(*interfaces): - """ - Declare interfaces implemented by instances of a class. - - .. deprecated:: 5.0 - This only works for Python 2. The `implementer` decorator - is preferred for all versions. - - This function is called in a class definition (Python 2.x only). - - The arguments are one or more interfaces or interface - specifications (`IDeclaration` objects). - - The interfaces given (including the interfaces in the - specifications) are added to any interfaces previously - declared. - - Previous declarations include declarations for base classes - unless implementsOnly was used. - - This function is provided for convenience. It provides a more - convenient way to call `classImplements`. For example:: - - implements(I1) - - is equivalent to calling:: - - classImplements(C, I1) - - after the class has been created. - - Consider the following example (Python 2.x only):: - - class C(A, B): - implements(I1, I2) - - - Instances of ``C`` implement ``I1``, ``I2``, and whatever interfaces - instances of ``A`` and ``B`` implement. - """ - - def implementsOnly(*interfaces): - """ - Declare the only interfaces implemented by instances of a class. - - .. deprecated:: 5.0 - This only works for Python 2. The `implementer_only` decorator - is preferred for all versions. - - This function is called in a class definition (Python 2.x only). - - The arguments are one or more interfaces or interface - specifications (`IDeclaration` objects). - - Previous declarations including declarations for base classes - are overridden. - - This function is provided for convenience. It provides a more - convenient way to call `classImplementsOnly`. For example:: - - implementsOnly(I1) - - is equivalent to calling:: - - classImplementsOnly(I1) - - after the class has been created. - - Consider the following example (Python 2.x only):: - - class C(A, B): - implementsOnly(I1, I2) - - - Instances of ``C`` implement ``I1``, ``I2``, regardless of what - instances of ``A`` and ``B`` implement. - """ - - def classProvides(*interfaces): - """ - Declare interfaces provided directly by a class. - - .. deprecated:: 5.0 - This only works for Python 2. The `provider` decorator - is preferred for all versions. - - This function is called in a class definition. - - The arguments are one or more interfaces or interface - specifications (`IDeclaration` objects). - - The given interfaces (including the interfaces in the - specifications) are used to create the class's direct-object - interface specification. An error will be raised if the module - class has an direct interface specification. In other words, it is - an error to call this function more than once in a class - definition. - - Note that the given interfaces have nothing to do with the - interfaces implemented by instances of the class. - - This function is provided for convenience. It provides a more - convenient way to call `directlyProvides` for a class. For example:: - - classProvides(I1) - - is equivalent to calling:: - - directlyProvides(theclass, I1) - - after the class has been created. - """ - def provider(*interfaces): """ - A class decorator version of `classProvides`. + Declare interfaces provided directly by a class. .. seealso:: `zope.interface.provider` """ @@ -934,7 +821,7 @@ provided interface, and a name, which must be text. """ - def registered(required, provided, name=u''): + def registered(required, provided, name=''): """Return the component registered for the given interfaces and name name must be text. @@ -956,11 +843,11 @@ text. """ - def queryMultiAdapter(objects, provided, name=u'', default=None): + def queryMultiAdapter(objects, provided, name='', default=None): """Adapt a sequence of objects to a named, provided, interface """ - def lookup1(required, provided, name=u'', default=None): + def lookup1(required, provided, name='', default=None): """Lookup a value using a single required interface A value is looked up based on a single required @@ -968,11 +855,11 @@ text. """ - def queryAdapter(object, provided, name=u'', default=None): # pylint:disable=redefined-builtin + def queryAdapter(object, provided, name='', default=None): # pylint:disable=redefined-builtin """Adapt an object using a registered adapter factory. """ - def adapter_hook(provided, object, name=u'', default=None): # pylint:disable=redefined-builtin + def adapter_hook(provided, object, name='', default=None): # pylint:disable=redefined-builtin """Adapt an object using a registered adapter factory. name must be text. @@ -1083,7 +970,7 @@ @implementer(IObjectEvent) -class ObjectEvent(object): +class ObjectEvent: def __init__(self, object): # pylint:disable=redefined-builtin self.object = object @@ -1102,26 +989,26 @@ utilities = Attribute( "Adapter Registry to manage all registered utilities.") - def queryAdapter(object, interface, name=u'', default=None): # pylint:disable=redefined-builtin + def queryAdapter(object, interface, name='', default=None): # pylint:disable=redefined-builtin """Look for a named adapter to an interface for an object If a matching adapter cannot be found, returns the default. """ - def getAdapter(object, interface, name=u''): # pylint:disable=redefined-builtin + def getAdapter(object, interface, name=''): # pylint:disable=redefined-builtin """Look for a named adapter to an interface for an object If a matching adapter cannot be found, a `ComponentLookupError` is raised. """ - def queryMultiAdapter(objects, interface, name=u'', default=None): + def queryMultiAdapter(objects, interface, name='', default=None): """Look for a multi-adapter to an interface for multiple objects If a matching adapter cannot be found, returns the default. """ - def getMultiAdapter(objects, interface, name=u''): + def getMultiAdapter(objects, interface, name=''): """Look for a multi-adapter to an interface for multiple objects If a matching adapter cannot be found, a `ComponentLookupError` @@ -1239,7 +1126,7 @@ """There has been a change in a registration """ def __repr__(self): - return "%s event:\n%r" % (self.__class__.__name__, self.object) + return "{} event:\n{!r}".format(self.__class__.__name__, self.object) class IRegistered(IRegistrationEvent): """A component or factory was registered @@ -1263,8 +1150,8 @@ """Register components """ - def registerUtility(component=None, provided=None, name=u'', - info=u'', factory=None): + def registerUtility(component=None, provided=None, name='', + info='', factory=None): """Register a utility :param factory: @@ -1291,7 +1178,7 @@ A `IRegistered` event is generated with an `IUtilityRegistration`. """ - def unregisterUtility(component=None, provided=None, name=u'', + def unregisterUtility(component=None, provided=None, name='', factory=None): """Unregister a utility @@ -1331,8 +1218,8 @@ in the object. """ - def registerAdapter(factory, required=None, provided=None, name=u'', - info=u''): + def registerAdapter(factory, required=None, provided=None, name='', + info=''): """Register an adapter factory :param factory: @@ -1367,7 +1254,7 @@ """ def unregisterAdapter(factory=None, required=None, - provided=None, name=u''): + provided=None, name=''): """Unregister an adapter factory :returns: @@ -1416,7 +1303,7 @@ """ def registerSubscriptionAdapter(factory, required=None, provides=None, - name=u'', info=''): + name='', info=''): """Register a subscriber factory :param factory: @@ -1454,7 +1341,7 @@ """ def unregisterSubscriptionAdapter(factory=None, required=None, - provides=None, name=u''): + provides=None, name=''): """Unregister a subscriber factory. :returns: @@ -1506,7 +1393,7 @@ registrations in the object. """ - def registerHandler(handler, required=None, name=u'', info=''): + def registerHandler(handler, required=None, name='', info=''): """Register a handler. A handler is a subscriber that doesn't compute an adapter @@ -1541,7 +1428,7 @@ A `IRegistered` event is generated with an `IHandlerRegistration`. """ - def unregisterHandler(handler=None, required=None, name=u''): + def unregisterHandler(handler=None, required=None, name=''): """Unregister a handler. A handler is a subscriber that doesn't compute an adapter
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/registry.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/registry.py
Changed
@@ -36,8 +36,6 @@ from zope.interface.declarations import implementer_only from zope.interface.declarations import providedBy from zope.interface.adapter import AdapterRegistry -from zope.interface._compat import CLASS_TYPES -from zope.interface._compat import STRING_TYPES __all__ = # Components is public API, but @@ -46,7 +44,7 @@ 'Components', -class _UnhashableComponentCounter(object): +class _UnhashableComponentCounter: # defaultdict(int)-like object for unhashable components def __init__(self, otherdict): @@ -76,7 +74,7 @@ def _defaultdict_int(): return defaultdict(int) -class _UtilityRegistrations(object): +class _UtilityRegistrations: def __init__(self, utilities, utility_registrations): # {provided -> {component: count}} @@ -144,14 +142,14 @@ @implementer(IComponents) -class Components(object): +class Components: _v_utility_registrations_cache = None def __init__(self, name='', bases=()): # __init__ is used for test cleanup as well as initialization. # XXX add a separate API for test cleanup. - assert isinstance(name, STRING_TYPES) + assert isinstance(name, str) self.__name__ = name self._init_registries() self._init_registrations() @@ -159,14 +157,14 @@ self._v_utility_registrations_cache = None def __repr__(self): - return "<%s %s>" % (self.__class__.__name__, self.__name__) + return "<{} {}>".format(self.__class__.__name__, self.__name__) def __reduce__(self): # Mimic what a persistent.Persistent object does and elide # _v_ attributes so that they don't get saved in ZODB. # This allows us to store things that cannot be pickled in such # attributes. - reduction = super(Components, self).__reduce__() + reduction = super().__reduce__() # (callable, args, state, listiter, dictiter) # We assume the state is always a dict; the last three items # are technically optional and can be missing or None. @@ -218,8 +216,8 @@ lambda self, bases: self._setBases(bases), ) - def registerUtility(self, component=None, provided=None, name=u'', - info=u'', event=True, factory=None): + def registerUtility(self, component=None, provided=None, name='', + info='', event=True, factory=None): if factory: if component: raise TypeError("Can't specify factory and component.") @@ -228,7 +226,7 @@ if provided is None: provided = _getUtilityProvided(component) - if name == u'': + if name == '': name = _getName(component) reg = self._utility_registrations.get((provided, name)) @@ -247,7 +245,7 @@ factory) )) - def unregisterUtility(self, component=None, provided=None, name=u'', + def unregisterUtility(self, component=None, provided=None, name='', factory=None): if factory: if component: @@ -283,28 +281,27 @@ ) in iter(self._utility_registrations.items()): yield UtilityRegistration(self, provided, name, *data) - def queryUtility(self, provided, name=u'', default=None): + def queryUtility(self, provided, name='', default=None): return self.utilities.lookup((), provided, name, default) - def getUtility(self, provided, name=u''): + def getUtility(self, provided, name=''): utility = self.utilities.lookup((), provided, name) if utility is None: raise ComponentLookupError(provided, name) return utility def getUtilitiesFor(self, interface): - for name, utility in self.utilities.lookupAll((), interface): - yield name, utility + yield from self.utilities.lookupAll((), interface) def getAllUtilitiesRegisteredFor(self, interface): return self.utilities.subscriptions((), interface) def registerAdapter(self, factory, required=None, provided=None, - name=u'', info=u'', event=True): + name='', info='', event=True): if provided is None: provided = _getAdapterProvided(factory) required = _getAdapterRequired(factory, required) - if name == u'': + if name == '': name = _getName(factory) self._adapter_registrations(required, provided, name) = factory, info @@ -318,7 +315,7 @@ def unregisterAdapter(self, factory=None, - required=None, provided=None, name=u'', + required=None, provided=None, name='', ): if provided is None: if factory is None: @@ -350,21 +347,21 @@ yield AdapterRegistration(self, required, provided, name, component, info) - def queryAdapter(self, object, interface, name=u'', default=None): + def queryAdapter(self, object, interface, name='', default=None): return self.adapters.queryAdapter(object, interface, name, default) - def getAdapter(self, object, interface, name=u''): + def getAdapter(self, object, interface, name=''): adapter = self.adapters.queryAdapter(object, interface, name) if adapter is None: raise ComponentLookupError(object, interface, name) return adapter - def queryMultiAdapter(self, objects, interface, name=u'', + def queryMultiAdapter(self, objects, interface, name='', default=None): return self.adapters.queryMultiAdapter( objects, interface, name, default) - def getMultiAdapter(self, objects, interface, name=u''): + def getMultiAdapter(self, objects, interface, name=''): adapter = self.adapters.queryMultiAdapter(objects, interface, name) if adapter is None: raise ComponentLookupError(objects, interface, name) @@ -380,7 +377,7 @@ def registerSubscriptionAdapter(self, factory, required=None, provided=None, - name=u'', info=u'', + name='', info='', event=True): if name: raise TypeError("Named subscribers are not yet supported") @@ -403,7 +400,7 @@ yield SubscriptionRegistration(self, *data) def unregisterSubscriptionAdapter(self, factory=None, - required=None, provided=None, name=u'', + required=None, provided=None, name='', ): if name: raise TypeError("Named subscribers are not yet supported") @@ -449,7 +446,7 @@ def registerHandler(self, factory, required=None, - name=u'', info=u'', + name='', info='', event=True): if name: raise TypeError("Named handlers are not yet supported") @@ -468,7 +465,7 @@ for data in self._handler_registrations: yield HandlerRegistration(self, *data) - def unregisterHandler(self, factory=None, required=None, name=u''): + def unregisterHandler(self, factory=None, required=None, name=''): if name: raise TypeError("Named subscribers are not yet supported") @@ -576,7 +573,7 @@ try: return component.__component_name__ except AttributeError: - return u'' + return '' def _getUtilityProvided(component): provided = list(providedBy(component)) @@ -612,7 +609,7 @@ if r is None: r = Interface elif not ISpecification.providedBy(r): - if isinstance(r, CLASS_TYPES): + if isinstance(r, type): r = implementedBy(r) else: raise TypeError("Required specification must be a " @@ -623,7 +620,7 @@ @implementer(IUtilityRegistration) -class UtilityRegistration(object): +class UtilityRegistration: def __init__(self, registry, provided, name, component, doc, factory=None): (self.registry, self.provided, self.name, self.component, self.info, @@ -631,7 +628,7 @@ ) = registry, provided, name, component, doc, factory def __repr__(self): - return '%s(%r, %s, %r, %s, %r, %r)' % ( + return '{}({!r}, {}, {!r}, {}, {!r}, {!r})'.format( self.__class__.__name__, self.registry, getattr(self.provided, '__name__', None), self.name, @@ -661,7 +658,7 @@ return repr(self) >= repr(other) @implementer(IAdapterRegistration) -class AdapterRegistration(object): +class AdapterRegistration: def __init__(self, registry, required, provided, name, component, doc): (self.registry, self.required, self.provided, self.name, @@ -669,7 +666,7 @@ ) = registry, required, provided, name, component, doc def __repr__(self): - return '%s(%r, %s, %s, %r, %s, %r)' % ( + return '{}({!r}, {}, {}, {!r}, {}, {!r})'.format( self.__class__.__name__, self.registry, '' + ", ".join(r.__name__ for r in self.required) + '', @@ -717,7 +714,7 @@ provided = None def __repr__(self): - return '%s(%r, %s, %r, %s, %r)' % ( + return '{}({!r}, {}, {!r}, {}, {!r})'.format( self.__class__.__name__, self.registry, '' + ", ".join(r.__name__ for r in self.required) + '',
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/ro.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/ro.py
Changed
@@ -80,7 +80,6 @@ output. The main thing to look for is changes in the relative positions of interfaces for which there are registered adapters. """ -from __future__ import print_function __docformat__ = 'restructuredtext' __all__ = @@ -178,7 +177,7 @@ def __str__(self): import pprint - return "%s: For object %r.\nBase ROs:\n%s\nConflict Location:\n%s" % ( + return "{}: For object {!r}.\nBase ROs:\n{}\nConflict Location:\n{}".format( self.__class__.__name__, self.C, pprint.pformat(self.base_ros), @@ -194,7 +193,7 @@ return inst -class _ClassBoolFromEnv(object): +class _ClassBoolFromEnv: """ Non-data descriptor that reads a transformed environment variable as a boolean, and caches the result in the class. @@ -221,7 +220,7 @@ return val -class _StaticMRO(object): +class _StaticMRO: # A previously resolved MRO, supplied by the caller. # Used in place of calculating it. @@ -235,7 +234,7 @@ return list(self.__mro) -class C3(object): +class C3: # Holds the shared state during computation of an MRO. @staticmethod @@ -465,19 +464,19 @@ return C3._guess_next_base(self, base_tree_remaining) -class _ROComparison(object): +class _ROComparison: # Exists to compute and print a pretty string comparison # for differing ROs. # Since we're used in a logging context, and may actually never be printed, # this is a class so we can defer computing the diff until asked. # Components we use to build up the comparison report - class Item(object): + class Item: prefix = ' ' def __init__(self, item): self.item = item def __str__(self): - return "%s%s" % ( + return "{}{}".format( self.prefix, self.item, ) @@ -490,7 +489,7 @@ Empty = str - class ReplacedBy(object): # pragma: no cover + class ReplacedBy: # pragma: no cover prefix = '- ' suffix = '' def __init__(self, chunk, total_count): @@ -541,7 +540,7 @@ if opcode == 'equal': # Guaranteed same length - c3_report.extend((self.Item(x) for x in c3_chunk)) + c3_report.extend(self.Item(x) for x in c3_chunk) legacy_report.extend(self.Item(x) for x in legacy_chunk) if opcode == 'delete': # Guaranteed same length @@ -583,9 +582,9 @@ max_left = max(len(x) for x in left_lines) max_right = max(len(x) for x in right_lines) - left_title = 'Legacy RO (len=%s)' % (len(self.legacy_ro),) + left_title = 'Legacy RO (len={})'.format(len(self.legacy_ro)) - right_title = 'C3 RO (len=%s; inconsistent=%s)' % ( + right_title = 'C3 RO (len={}; inconsistent={})'.format( len(self.c3_ro), self._inconsistent_label, )
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/tests/__init__.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/tests/__init__.py
Changed
@@ -1,7 +1,7 @@ from zope.interface._compat import _should_attempt_c_optimizations -class OptimizationTestMixin(object): +class OptimizationTestMixin: """ Helper for testing that C optimizations are used when appropriate. @@ -33,7 +33,7 @@ self.assertIs(used, fallback) -class MissingSomeAttrs(object): +class MissingSomeAttrs: """ Helper for tests that raises a specific exception for attributes that are missing. This is usually not @@ -106,7 +106,7 @@ try: from zope.testing import cleanup except ImportError: - class CleanUp(object): + class CleanUp: def cleanUp(self): pass
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/tests/advisory_testing.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/tests/advisory_testing.py
Changed
@@ -13,27 +13,11 @@ ############################################################################## import sys -from zope.interface.advice import addClassAdvisor from zope.interface.advice import getFrameInfo my_globals = globals() -def ping(log, value): - - def pong(klass): - log.append((value,klass)) - return klass - - addClassAdvisor(pong) - -try: - from types import ClassType - - class ClassicClass: - __metaclass__ = ClassType - classLevelFrameInfo = getFrameInfo(sys._getframe()) -except ImportError: - ClassicClass = None +ClassicClass = None class NewStyleClass: __metaclass__ = type
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/tests/odd.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/tests/odd.py
Changed
@@ -55,10 +55,6 @@ >>> C.c = 1 >>> c.c 1 - >>> import sys - >>> if sys.version0 == '2': # This test only makes sense under Python 2.x - ... from types import ClassType - ... assert not isinstance(C, (type, ClassType)) >>> int(C.__class__.__class__ is C.__class__) 1 @@ -75,7 +71,7 @@ return type.__getattribute__(cls, name) -class MetaClass(object): +class MetaClass: """Odd classes """ @@ -95,7 +91,7 @@ raise AttributeError(name) def __repr__(self): # pragma: no cover - return "<odd class %s at %s>" % (self.__name__, hex(id(self))) + return "<odd class {} at {}>".format(self.__name__, hex(id(self))) MetaClass = MetaMetaClass('MetaClass', @@ -103,7 +99,7 @@ {k: v for k, v in MetaClass.__dict__.items() if k not in ('__dict__',)}) -class OddInstance(object): +class OddInstance: def __init__(self, cls): self.__dict__'__class__' = cls @@ -124,5 +120,5 @@ raise NotImplementedError() def __repr__(self): # pragma: no cover - return "<odd %s instance at %s>" % ( + return "<odd {} instance at {}>".format( self.__class__.__name__, hex(id(self)))
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/tests/test_adapter.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/tests/test_adapter.py
Changed
@@ -50,7 +50,7 @@ # Custom types to use as part of the AdapterRegistry data structures. # Our custom types do strict type checking to make sure # types propagate through the data tree as expected. -class CustomDataTypeBase(object): +class CustomDataTypeBase: _data = None def __getitem__(self, name): return self._dataname @@ -112,7 +112,7 @@ def _getTargetClass(self): BaseAdapterRegistry = self._getBaseAdapterRegistry() class _CUT(BaseAdapterRegistry): - class LookupClass(object): + class LookupClass: _changed = _extendors = () def __init__(self, reg): pass @@ -162,7 +162,7 @@ self.assertEqual(registry._v_lookup._changed, (registry, orig,)) def test__generation_after_changing___bases__(self): - class _Base(object): + class _Base: pass registry = self._makeOne() registry.__bases__ = (_Base,) @@ -1132,7 +1132,7 @@ return context def _lookup(self, required, provided, name=''): return _factory - required = super(LookupBaseFallbackTests, self) + required = super() provided = object() lb = self._makeOne(uc_lookup=_lookup) adapted = lb.adapter_hook(provided, required) @@ -1233,14 +1233,14 @@ _uncached_lookupAll = uc_lookupAll _uncached_subscriptions = uc_subscriptions def __init__(self, registry): - super(Derived, self).__init__() + super().__init__() self._registry = registry derived = Derived(registry) derived.changed(derived) # init. '_verify_ro' / '_verify_generations' return derived def _makeRegistry(self, depth): - class WithGeneration(object): + class WithGeneration: _generation = 1 class Registry: def __init__(self, depth): @@ -1418,7 +1418,7 @@ def test_changed_empty_required(self): # ALB.changed expects to call a mixed in changed. - class Mixin(object): + class Mixin: def changed(self, *other): pass class Derived(self._getTargetClass(), Mixin): @@ -1429,12 +1429,12 @@ def test_changed_w_required(self): # ALB.changed expects to call a mixed in changed. - class Mixin(object): + class Mixin: def changed(self, *other): pass class Derived(self._getTargetClass(), Mixin): pass - class FauxWeakref(object): + class FauxWeakref: _unsub = None def __init__(self, here): self._here = here @@ -1617,7 +1617,7 @@ IFoo = InterfaceClass('IFoo') IBar = InterfaceClass('IBar', (IFoo,)) @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() registry = self._makeRegistry() @@ -1653,9 +1653,7 @@ IFoo, ) - PY3 = str is not bytes - MissingSomeAttrs.test_raises(self, test, - expected_missing='__class__' if PY3 else '__providedBy__') + MissingSomeAttrs.test_raises(self, test, expected_missing='__class__') def test_queryMultiAdaptor_factory_miss(self): from zope.interface.declarations import implementer @@ -1663,7 +1661,7 @@ IFoo = InterfaceClass('IFoo') IBar = InterfaceClass('IBar', (IFoo,)) @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() registry = self._makeRegistry(IFoo, IBar) @@ -1692,7 +1690,7 @@ IFoo = InterfaceClass('IFoo') IBar = InterfaceClass('IBar', (IFoo,)) @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() registry = self._makeRegistry(IFoo, IBar) @@ -1724,10 +1722,10 @@ alb.lookup = lookup objects = - super(AdapterLookupBaseTests, self), + super(), 42, "abc", - super(AdapterLookupBaseTests, self), + super(), result = alb.queryMultiAdapter(objects, None) @@ -1906,7 +1904,7 @@ IBar = InterfaceClass('IBar', (IFoo,)) registry = self._makeRegistry(IFoo, IBar) subr = self._makeSubregistry() - class Foo(object): + class Foo: def __lt__(self, other): return True _exp1, _exp2 = Foo(), Foo() @@ -1926,7 +1924,7 @@ IFoo = InterfaceClass('IFoo') IBar = InterfaceClass('IBar', (IFoo,)) @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() registry = self._makeRegistry(IFoo, IBar) @@ -1955,7 +1953,7 @@ IFoo = InterfaceClass('IFoo') IBar = InterfaceClass('IBar', (IFoo,)) @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() registry = self._makeRegistry(IFoo, IBar) @@ -2061,7 +2059,7 @@ def test_changed_w_subregistries(self): base = self._makeOne() - class Derived(object): + class Derived: _changed = None def changed(self, originally_changed): self._changed = originally_changed @@ -2089,7 +2087,7 @@ def test__normalize_name_str(self): from zope.interface.adapter import _normalize_name STR = b'str' - UNICODE = u'str' + UNICODE = 'str' norm = _normalize_name(STR) self.assertEqual(norm, UNICODE) self.assertIsInstance(norm, type(UNICODE)) @@ -2097,7 +2095,7 @@ def test__normalize_name_unicode(self): from zope.interface.adapter import _normalize_name - USTR = u'ustr' + USTR = 'ustr' self.assertEqual(_normalize_name(USTR), USTR) def test__normalize_name_other(self):
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/tests/test_advice.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/tests/test_advice.py
Changed
@@ -28,9 +28,6 @@ import unittest import sys -from zope.interface._compat import _skip_under_py2 -from zope.interface._compat import _skip_under_py3k - class FrameInfoTest(unittest.TestCase): @@ -42,21 +39,7 @@ for d in module.__dict__, f_locals, f_globals: self.assertTrue(d is advisory_testing.my_globals) - @_skip_under_py3k - def test_w_ClassicClass(self): - from zope.interface.tests import advisory_testing - (kind, - module, - f_locals, - f_globals) = advisory_testing.ClassicClass.classLevelFrameInfo - self.assertEqual(kind, "class") - - self.assertTrue( - f_locals is advisory_testing.ClassicClass.__dict__) # ??? - for d in module.__dict__, f_globals: - self.assertTrue(d is advisory_testing.my_globals) - - def test_w_NewStyleClass(self): + def test_w_class(self): from zope.interface.tests import advisory_testing (kind, module, @@ -91,83 +74,6 @@ kind, module, f_locals, f_globals = getFrameInfo(sys._getframe()) """ -class AdviceTests(unittest.TestCase): - - @_skip_under_py3k - def test_order(self): - from zope.interface.tests.advisory_testing import ping - log = - class Foo(object): - ping(log, 1) - ping(log, 2) - ping(log, 3) - - # Strip the list nesting - for i in 1, 2, 3: - self.assertTrue(isinstance(Foo, list)) - Foo, = Foo - - self.assertEqual(log, (1, Foo), (2, Foo), (3, Foo)) - - @_skip_under_py3k - def test_single_explicit_meta(self): - from zope.interface.tests.advisory_testing import ping - - class Metaclass(type): - pass - - class Concrete(Metaclass): - __metaclass__ = Metaclass - ping(,1) - - Concrete, = Concrete - self.assertTrue(Concrete.__class__ is Metaclass) - - - @_skip_under_py3k - def test_mixed_metas(self): - from zope.interface.tests.advisory_testing import ping - - class Metaclass1(type): - pass - - class Metaclass2(type): - pass - - class Base1: - __metaclass__ = Metaclass1 - - class Base2: - __metaclass__ = Metaclass2 - - try: - class Derived(Base1, Base2): - ping(, 1) - self.fail("Should have gotten incompatibility error") - except TypeError: - pass - - class Metaclass3(Metaclass1, Metaclass2): - pass - - class Derived(Base1, Base2): - __metaclass__ = Metaclass3 - ping(, 1) - - self.assertTrue(isinstance(Derived, list)) - Derived, = Derived - self.assertTrue(isinstance(Derived, Metaclass3)) - - @_skip_under_py3k - def test_meta_no_bases(self): - from zope.interface.tests.advisory_testing import ping - from types import ClassType - class Thing: - ping(, 1) - klass, = Thing # unpack list created by pong - self.assertEqual(type(klass), ClassType) - - class Test_isClassAdvisor(unittest.TestCase): def _callFUT(self, *args, **kw): @@ -195,11 +101,6 @@ from zope.interface.advice import determineMetaclass return determineMetaclass(*args, **kw) - @_skip_under_py3k - def test_empty(self): - from types import ClassType - self.assertEqual(self._callFUT(()), ClassType) - def test_empty_w_explicit_metatype(self): class Meta(type): pass @@ -210,96 +111,43 @@ pass self.assertEqual(self._callFUT((Meta,)), type) - @_skip_under_py3k def test_meta_of_class(self): class Metameta(type): pass - - class Meta(type): - __metaclass__ = Metameta - - self.assertEqual(self._callFUT((Meta, type)), Metameta) - - @_skip_under_py2 - def test_meta_of_class_py3k(self): - # Work around SyntaxError under Python2. - EXEC = '\n'.join( - 'class Metameta(type):', - ' pass', - 'class Meta(type, metaclass=Metameta):', - ' pass', - ) - globs = {} - exec(EXEC, globs) - Meta = globs'Meta' - Metameta = globs'Metameta' + class Meta(type, metaclass=Metameta): + pass self.assertEqual(self._callFUT((Meta, type)), Metameta) - @_skip_under_py3k - def test_multiple_in_hierarchy(self): + def test_multiple_in_hierarchy_py3k(self): class Meta_A(type): pass + class Meta_B(Meta_A): pass - class A(type): - __metaclass__ = Meta_A - class B(type): - __metaclass__ = Meta_B - self.assertEqual(self._callFUT((A, B,)), Meta_B) - @_skip_under_py2 - def test_multiple_in_hierarchy_py3k(self): - # Work around SyntaxError under Python2. - EXEC = '\n'.join( - 'class Meta_A(type):', - ' pass', - 'class Meta_B(Meta_A):', - ' pass', - 'class A(type, metaclass=Meta_A):', - ' pass', - 'class B(type, metaclass=Meta_B):', - ' pass', - ) - globs = {} - exec(EXEC, globs) - Meta_A = globs'Meta_A' - Meta_B = globs'Meta_B' - A = globs'A' - B = globs'B' + class A(type, metaclass=Meta_A): + pass + + class B(type, metaclass=Meta_B): + pass + self.assertEqual(self._callFUT((A, B)), Meta_B) - @_skip_under_py3k - def test_multiple_not_in_hierarchy(self): + + def test_multiple_not_in_hierarchy_py3k(self): class Meta_A(type): pass + class Meta_B(type): pass - class A(type): - __metaclass__ = Meta_A - class B(type): - __metaclass__ = Meta_B - self.assertRaises(TypeError, self._callFUT, (A, B,)) - @_skip_under_py2 - def test_multiple_not_in_hierarchy_py3k(self): - # Work around SyntaxError under Python2. - EXEC = '\n'.join( - 'class Meta_A(type):', - ' pass', - 'class Meta_B(type):', - ' pass', - 'class A(type, metaclass=Meta_A):', - ' pass', - 'class B(type, metaclass=Meta_B):', - ' pass', - ) - globs = {} - exec(EXEC, globs) - Meta_A = globs'Meta_A' - Meta_B = globs'Meta_B' - A = globs'A' - B = globs'B' + class A(type, metaclass=Meta_A): + pass + + class B(type, metaclass=Meta_B): + pass + self.assertRaises(TypeError, self._callFUT, (A, B)) @@ -312,34 +160,22 @@ def test_empty(self): self.assertEqual(self._callFUT(), ) - @_skip_under_py3k - def test_w_oldstyle_meta(self): - class C: - pass - self.assertEqual(self._callFUT(type(C)), ) - - @_skip_under_py3k - def test_w_oldstyle_class(self): - class C: - pass - self.assertEqual(self._callFUT(C), C) - def test_w_newstyle_meta(self): self.assertEqual(self._callFUT(type), type) def test_w_newstyle_class(self): - class C(object): + class C: pass self.assertEqual(self._callFUT(C), C) def test_simple_hierarchy_skips_implied(self): - class A(object): + class A: pass class B(A): pass class C(B): pass - class D(object): + class D: pass self.assertEqual(self._callFUT(A, B, C), C) self.assertEqual(self._callFUT(A, C), C) @@ -348,8 +184,8 @@ self.assertEqual(self._callFUT(D, B, D), B, D) def test_repeats_kicked_to_end_of_queue(self): - class A(object): + class A: pass - class B(object): + class B: pass self.assertEqual(self._callFUT(A, B, A), B, A)
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/tests/test_declarations.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/tests/test_declarations.py
Changed
@@ -15,8 +15,6 @@ """ import unittest -from zope.interface._compat import _skip_under_py3k -from zope.interface._compat import PYTHON3 from zope.interface.tests import OptimizationTestMixin from zope.interface.tests import MissingSomeAttrs from zope.interface.tests.test_interface import NameAndModuleComparisonTestsMixin @@ -24,7 +22,7 @@ # pylint:disable=inherit-non-class,too-many-lines,protected-access # pylint:disable=blacklisted-name,attribute-defined-outside-init -class _Py3ClassAdvice(object): +class _Py3ClassAdvice: def _run_generated_code(self, code, globs, locs, fails_under_py3k=True, @@ -33,10 +31,6 @@ import warnings with warnings.catch_warnings(record=True) as log: warnings.resetwarnings() - if not PYTHON3: - exec(code, globs, locs) - self.assertEqual(len(log), 0) # no longer warn - return True try: exec(code, globs, locs) @@ -53,30 +47,30 @@ def test_class(self): from zope.interface.declarations import named - @named(u'foo') - class Foo(object): + @named('foo') + class Foo: pass - self.assertEqual(Foo.__component_name__, u'foo') # pylint:disable=no-member + self.assertEqual(Foo.__component_name__, 'foo') # pylint:disable=no-member def test_function(self): from zope.interface.declarations import named - @named(u'foo') + @named('foo') def doFoo(o): raise NotImplementedError() - self.assertEqual(doFoo.__component_name__, u'foo') + self.assertEqual(doFoo.__component_name__, 'foo') def test_instance(self): from zope.interface.declarations import named - class Foo(object): + class Foo: pass foo = Foo() - named(u'foo')(foo) + named('foo')(foo) - self.assertEqual(foo.__component_name__, u'foo') # pylint:disable=no-member + self.assertEqual(foo.__component_name__, 'foo') # pylint:disable=no-member class EmptyDeclarationTests(unittest.TestCase): @@ -329,7 +323,7 @@ pass @implementer(IBase) - class Base(object): + class Base: pass with C3Setting(ro.C3.STRICT_IRO, True): @@ -419,7 +413,7 @@ def _makeOneToCompare(self): from zope.interface.declarations import implementedBy - class A(object): + class A: pass return implementedBy(A) @@ -443,9 +437,9 @@ def test_sort(self): from zope.interface.declarations import implementedBy - class A(object): + class A: pass - class B(object): + class B: pass from zope.interface.interface import InterfaceClass IFoo = InterfaceClass('IFoo') @@ -462,7 +456,7 @@ def test_proxy_equality(self): # https://github.com/zopefoundation/zope.interface/issues/55 - class Proxy(object): + class Proxy: def __init__(self, wrapped): self._wrapped = wrapped @@ -476,10 +470,10 @@ return self._wrapped != other from zope.interface.declarations import implementedBy - class A(object): + class A: pass - class B(object): + class B: pass implementedByA = implementedBy(A) @@ -535,14 +529,14 @@ return self._getTargetClass()(*args, **kw) def test_dictless_wo_existing_Implements_wo_registrations(self): - class Foo(object): + class Foo: __slots__ = ('__implemented__',) foo = Foo() foo.__implemented__ = None self.assertEqual(list(self._callFUT(foo)), ) def test_dictless_wo_existing_Implements_cant_assign___implemented__(self): - class Foo(object): + class Foo: def _get_impl(self): raise NotImplementedError() def _set_impl(self, val): @@ -556,7 +550,7 @@ def test_dictless_wo_existing_Implements_w_registrations(self): from zope.interface import declarations - class Foo(object): + class Foo: __slots__ = ('__implemented__',) foo = Foo() foo.__implemented__ = None @@ -569,7 +563,7 @@ def test_dictless_w_existing_Implements(self): from zope.interface.declarations import Implements impl = Implements() - class Foo(object): + class Foo: __slots__ = ('__implemented__',) foo = Foo() foo.__implemented__ = impl @@ -577,7 +571,7 @@ def test_dictless_w_existing_not_Implements(self): from zope.interface.interface import InterfaceClass - class Foo(object): + class Foo: __slots__ = ('__implemented__',) foo = Foo() IFoo = InterfaceClass('IFoo') @@ -587,7 +581,7 @@ def test_w_existing_attr_as_Implements(self): from zope.interface.declarations import Implements impl = Implements() - class Foo(object): + class Foo: __implemented__ = impl self.assertTrue(self._callFUT(Foo) is impl) @@ -626,19 +620,19 @@ def test_no_assertions(self): # TODO: Figure out P3 story - class Foo(object): + class Foo: pass self.assertEqual(list(self._callFUT(Foo)), ) def test_w_None_no_bases_not_factory(self): - class Foo(object): + class Foo: __implemented__ = None foo = Foo() self.assertRaises(TypeError, self._callFUT, foo) def test_w_None_no_bases_w_factory(self): from zope.interface.declarations import objectSpecificationDescriptor - class Foo(object): + class Foo: __implemented__ = None def __call__(self): raise NotImplementedError() @@ -655,7 +649,7 @@ def test_w_None_no_bases_w_class(self): from zope.interface.declarations import ClassProvides - class Foo(object): + class Foo: __implemented__ = None spec = self._callFUT(Foo) self.assertEqual(spec.__name__, @@ -669,7 +663,7 @@ def test_w_existing_Implements(self): from zope.interface.declarations import Implements impl = Implements() - class Foo(object): + class Foo: __implemented__ = impl self.assertTrue(self._callFUT(Foo) is impl) @@ -684,7 +678,7 @@ pass @implementer(IBase) - class Base(object): + class Base: pass @implementer(IDerived) @@ -706,7 +700,7 @@ pass @implementer(IBase) - class Base(object): + class Base: pass class Child1(Base): @@ -734,7 +728,7 @@ pass - class Base(object): + class Base: pass class Child1(Base): @@ -765,7 +759,7 @@ class IDerived(IBase): pass - class Base(object): + class Base: pass @implementer(IDerived) @@ -788,7 +782,7 @@ pass @implementer(IDerived) - class Derived(object): + class Derived: pass self.assertEqual(list(self._callFUT(Derived)), IDerived) @@ -815,7 +809,7 @@ pass @implementer(IBase) - class Base(object): + class Base: pass @implementer(IM1) @@ -854,7 +848,7 @@ return implementedBy -class _ImplementsTestMixin(object): +class _ImplementsTestMixin: FUT_SETS_PROVIDED_BY = True def _callFUT(self, cls, iface): @@ -888,17 +882,11 @@ return Foo, IFoo - def test_oldstyle_class(self): - # This only matters on Python 2 + def test_class(self): class Foo: pass self._check_implementer(Foo) - def test_newstyle_class(self): - class Foo(object): - pass - self._check_implementer(Foo) - class Test_classImplementsOnly(_ImplementsTestMixin, unittest.TestCase): FUT_SETS_PROVIDED_BY = False @@ -914,7 +902,7 @@ IBar = InterfaceClass('IBar') impl = Implements(IFoo) impl.declared = (IFoo,) - class Foo(object): + class Foo: __implemented__ = impl impl.inherit = Foo self._callFUT(Foo, IBar) @@ -923,7 +911,7 @@ self.assertEqual(impl.inherit, None) self.assertEqual(impl.declared, (IBar,)) - def test_oldstyle_class(self): + def test_class(self): from zope.interface.declarations import Implements from zope.interface.interface import InterfaceClass IBar = InterfaceClass('IBar') @@ -933,16 +921,6 @@ __implemented__ = old_spec self._check_implementer(Foo, old_spec, '?', inherit=None) - def test_newstyle_class(self): - from zope.interface.declarations import Implements - from zope.interface.interface import InterfaceClass - IBar = InterfaceClass('IBar') - old_spec = Implements(IBar) - - class Foo(object): - __implemented__ = old_spec - self._check_implementer(Foo, old_spec, '?', inherit=None) - def test_redundant_with_super_still_implements(self): Base, IBase = self._check_implementer( @@ -984,11 +962,7 @@ self.assertTrue(IBase.providedBy(Child())) - def test_redundant_implementer_empty_class_declarations_newstyle(self): - self.__check_implementer_redundant(type('Foo', (object,), {})) - - def test_redundant_implementer_empty_class_declarations_oldstyle(self): - # This only matters on Python 2 + def test_redundant_implementer_empty_class_declarations(self): class Foo: pass self.__check_implementer_redundant(Foo) @@ -999,7 +973,7 @@ from zope.interface import ro from zope.interface.tests.test_ro import C3Setting - class Foo(object): + class Foo: pass with C3Setting(ro.C3.STRICT_IRO, False): @@ -1022,7 +996,7 @@ IBar = InterfaceClass('IBar') impl = Implements(IFoo) impl.declared = (IFoo,) - class Foo(object): + class Foo: __implemented__ = impl impl.inherit = Foo self._callFUT(Foo, IBar) @@ -1042,9 +1016,9 @@ impl_root = Implements.named('Root', IRoot) impl_root.declared = (IRoot,) - class Root1(object): + class Root1: __implemented__ = impl_root - class Root2(object): + class Root2: __implemented__ = impl_root impl_extends_root = Implements.named('ExtendsRoot1', IExtendsRoot) @@ -1086,7 +1060,7 @@ from zope.interface.declarations import Implements from zope.interface.interface import InterfaceClass IFoo = InterfaceClass('IFoo') - class Foo(object): + class Foo: __implements_advice_data__ = ((IFoo,), classImplements) self._callFUT(Foo) self.assertNotIn('__implements_advice_data__', Foo.__dict__) @@ -1116,7 +1090,7 @@ def test_nonclass_can_assign_attr(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass('IFoo') - class Foo(object): + class Foo: pass foo = Foo() decorator = self._makeOne(IFoo) @@ -1140,7 +1114,7 @@ begin_count = len(gc.get_objects()) for _ in range(1900): - class TestClass(object): + class TestClass: pass self._callFUT(TestClass, IFoo) @@ -1190,118 +1164,6 @@ -# Test '_implements' by way of 'implements{,Only}', its only callers. - -class Test_implementsOnly(unittest.TestCase, _Py3ClassAdvice): - - def test_simple(self): - import warnings - from zope.interface.declarations import implementsOnly - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - globs = {'implementsOnly': implementsOnly, - 'IFoo': IFoo, - } - locs = {} - CODE = "\n".join( - 'class Foo(object):' - ' implementsOnly(IFoo)', - ) - with warnings.catch_warnings(record=True) as log: - warnings.resetwarnings() - try: - exec(CODE, globs, locs) # pylint:disable=exec-used - except TypeError: - self.assertTrue(PYTHON3, "Must be Python 3") - else: - if PYTHON3: - self.fail("Didn't raise TypeError") - Foo = locs'Foo' - spec = Foo.__implemented__ - self.assertEqual(list(spec), IFoo) - self.assertEqual(len(log), 0) # no longer warn - - def test_called_once_from_class_w_bases(self): - from zope.interface.declarations import implements - from zope.interface.declarations import implementsOnly - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - IBar = InterfaceClass("IBar") - globs = {'implements': implements, - 'implementsOnly': implementsOnly, - 'IFoo': IFoo, - 'IBar': IBar, - } - locs = {} - CODE = "\n".join( - 'class Foo(object):', - ' implements(IFoo)', - 'class Bar(Foo):' - ' implementsOnly(IBar)', - ) - if self._run_generated_code(CODE, globs, locs): - Bar = locs'Bar' - spec = Bar.__implemented__ - self.assertEqual(list(spec), IBar) - - -class Test_implements(unittest.TestCase, _Py3ClassAdvice): - - def test_called_from_function(self): - import warnings - from zope.interface.declarations import implements - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - globs = {'implements': implements, 'IFoo': IFoo} - locs = {} - CODE = "\n".join( - 'def foo():', - ' implements(IFoo)' - ) - if self._run_generated_code(CODE, globs, locs, False): - foo = locs'foo' - with warnings.catch_warnings(record=True) as log: - warnings.resetwarnings() - self.assertRaises(TypeError, foo) - self.assertEqual(len(log), 0) # no longer warn - - def test_called_twice_from_class(self): - import warnings - from zope.interface.declarations import implements - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - IBar = InterfaceClass("IBar") - globs = {'implements': implements, 'IFoo': IFoo, 'IBar': IBar} - locs = {} - CODE = "\n".join( - 'class Foo(object):', - ' implements(IFoo)', - ' implements(IBar)', - ) - with warnings.catch_warnings(record=True) as log: - warnings.resetwarnings() - try: - exec(CODE, globs, locs) # pylint:disable=exec-used - except TypeError: - if not PYTHON3: - self.assertEqual(len(log), 0) # no longer warn - else: - self.fail("Didn't raise TypeError") - - def test_called_once_from_class(self): - from zope.interface.declarations import implements - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - globs = {'implements': implements, 'IFoo': IFoo} - locs = {} - CODE = "\n".join( - 'class Foo(object):', - ' implements(IFoo)', - ) - if self._run_generated_code(CODE, globs, locs): - Foo = locs'Foo' - spec = Foo.__implemented__ - self.assertEqual(list(spec), IFoo) class ProvidesClassTests(unittest.TestCase): @@ -1316,7 +1178,7 @@ def test_simple_class_one_interface(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass spec = self._makeOne(Foo, IFoo) self.assertEqual(list(spec), IFoo) @@ -1325,7 +1187,7 @@ from zope.interface.declarations import Provides # the function from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass spec = self._makeOne(Foo, IFoo) klass, args = spec.__reduce__() @@ -1335,7 +1197,7 @@ def test___get___class(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass spec = self._makeOne(Foo, IFoo) Foo.__provides__ = spec @@ -1344,7 +1206,7 @@ def test___get___instance(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass spec = self._makeOne(Foo, IFoo) Foo.__provides__ = spec @@ -1358,7 +1220,7 @@ # Tests that require the strict C3 resolution order. def _getTargetClass(self): - ProvidesClass = super(ProvidesClassStrictTests, self)._getTargetClass() + ProvidesClass = super()._getTargetClass() class StrictProvides(ProvidesClass): def _do_calculate_ro(self, base_mros): return ProvidesClass._do_calculate_ro(self, base_mros=base_mros, strict=True) @@ -1375,7 +1237,7 @@ pass @implementer(IBase) - class Base(object): + class Base: pass spec = self._makeOne(Base, IBase) @@ -1402,7 +1264,7 @@ IFoo = InterfaceClass("IFoo") assert IFoo.__name__ == 'IFoo' assert IFoo.__module__ == __name__ - assert repr(IFoo) == '<InterfaceClass %s.IFoo>' % (__name__,) + assert repr(IFoo) == '<InterfaceClass {}.IFoo>'.format(__name__) IBar = InterfaceClass("IBar") @@ -1507,7 +1369,7 @@ class IFoo(Interface): "Does nothing" - class Bar(object): + class Bar: "Does nothing" impl = implementedBy(type(self)) @@ -1526,7 +1388,7 @@ ) def test__repr__non_class(self): - class Object(object): + class Object: __bases__ = () __str__ = lambda _: self.fail("Should not call str") @@ -1545,7 +1407,7 @@ IFoo = InterfaceClass("IFoo") @implementer(IFoo) - class Foo(object): + class Foo: pass inst = providedBy(Foo()) @@ -1563,7 +1425,7 @@ IBar = InterfaceClass("IBar") @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() @@ -1588,7 +1450,7 @@ from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") cache = {} - class Foo(object): + class Foo: pass with _Monkey(declarations, InstanceDeclarations=cache): spec = self._callFUT(Foo, IFoo) @@ -1600,7 +1462,7 @@ from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") prior = object() - class Foo(object): + class Foo: pass cache = {(Foo, IFoo): prior} with _Monkey(declarations, InstanceDeclarations=cache): @@ -1618,7 +1480,7 @@ from zope.interface.declarations import ProvidesClass from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass obj = Foo() self._callFUT(obj, IFoo) @@ -1629,37 +1491,18 @@ from zope.interface.declarations import ClassProvides from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass self._callFUT(Foo, IFoo) self.assertIsInstance(Foo.__provides__, ClassProvides) # pylint:disable=no-member self.assertEqual(list(Foo.__provides__), IFoo) # pylint:disable=no-member - @_skip_under_py3k - def test_w_non_descriptor_aware_metaclass(self): - # There are no non-descriptor-aware types in Py3k - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - class MetaClass(type): - def __getattribute__(cls, name): - # Emulate metaclass whose base is not the type object. - if name == '__class__': - return cls - # Under certain circumstances, the implementedByFallback - # can get here for __dict__ - return type.__getattribute__(cls, name) # pragma: no cover - - class Foo(object): - __metaclass__ = MetaClass - obj = Foo() - self.assertRaises(TypeError, self._callFUT, obj, IFoo) - def test_w_classless_object(self): from zope.interface.declarations import ProvidesClass from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") the_dict = {} - class Foo(object): + class Foo: def __getattribute__(self, name): # Emulate object w/o any class if name == '__class__': @@ -1683,7 +1526,7 @@ from zope.interface.declarations import ProvidesClass from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass obj = Foo() self._callFUT(obj, IFoo) @@ -1696,7 +1539,7 @@ from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") IBar = InterfaceClass("IBar") - class Foo(object): + class Foo: pass obj = Foo() directlyProvides(obj, IFoo) @@ -1714,7 +1557,7 @@ def test_wo_existing_provides(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass obj = Foo() self._callFUT(obj, IFoo) @@ -1724,7 +1567,7 @@ from zope.interface.declarations import directlyProvides from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass obj = Foo() directlyProvides(obj, IFoo) @@ -1736,7 +1579,7 @@ from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") IBar = InterfaceClass("IBar") - class Foo(object): + class Foo: pass obj = Foo() directlyProvides(obj, IFoo) @@ -1748,7 +1591,7 @@ from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") @implementer(IFoo) - class Foo(object): + class Foo: pass obj = Foo() self.assertRaises(ValueError, self._callFUT, obj, IFoo) @@ -1773,7 +1616,7 @@ def test_w_same_class_via_class(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass cpbp = Foo.__provides__ = self._makeOne(Foo, IFoo) self.assertTrue(Foo.__provides__ is cpbp) @@ -1781,7 +1624,7 @@ def test_w_same_class_via_instance(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass foo = Foo() Foo.__provides__ = self._makeOne(Foo, IFoo) @@ -1790,7 +1633,7 @@ def test_w_different_class(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass class Bar(Foo): pass @@ -1829,7 +1672,7 @@ IFoo = InterfaceClass("IFoo") IBar = InterfaceClass("IBar") @implementer(IFoo) - class Foo(object): + class Foo: pass cp = Foo.__provides__ = self._makeOne(Foo, type(Foo), IBar) self.assertTrue(Foo.__provides__ is cp) @@ -1841,7 +1684,7 @@ IFoo = InterfaceClass("IFoo") IBar = InterfaceClass("IBar") @implementer(IFoo) - class Foo(object): + class Foo: pass cp = Foo.__provides__ = self._makeOne(Foo, type(Foo), IBar) self.assertEqual(cp.__reduce__(), @@ -1852,7 +1695,7 @@ # Tests that require the strict C3 resolution order. def _getTargetClass(self): - ClassProvides = super(ClassProvidesStrictTests, self)._getTargetClass() + ClassProvides = super()._getTargetClass() class StrictClassProvides(ClassProvides): def _do_calculate_ro(self, base_mros): return ClassProvides._do_calculate_ro(self, base_mros=base_mros, strict=True) @@ -1935,7 +1778,7 @@ IFoo = InterfaceClass("IFoo") @implementer(IFoo) - class Foo(object): + class Foo: pass inst = implementedBy(Foo) @@ -1948,14 +1791,14 @@ from zope.interface.declarations import implementedBy # We can't get a __name__ by default, so we get a # module name and a question mark - class Callable(object): + class Callable: def __call__(self): return self inst = implementedBy(Callable()) self.assertEqual( repr(inst), - 'classImplements(%s.?)' % (__name__,) + 'classImplements({}.?)'.format(__name__) ) c = Callable() @@ -1974,7 +1817,7 @@ return directlyProvidedBy(*args, **kw) def test_wo_declarations_in_class_or_instance(self): - class Foo(object): + class Foo: pass foo = Foo() self.assertEqual(list(self._callFUT(foo)), ) @@ -1984,7 +1827,7 @@ from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() self.assertEqual(list(self._callFUT(foo)), ) @@ -1993,7 +1836,7 @@ from zope.interface.declarations import directlyProvides from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass foo = Foo() directlyProvides(foo, IFoo) @@ -2006,76 +1849,13 @@ IFoo = InterfaceClass("IFoo") IBar = InterfaceClass("IBar") @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() directlyProvides(foo, IBar) self.assertEqual(list(self._callFUT(foo)), IBar) -class Test_classProvides(unittest.TestCase, _Py3ClassAdvice): - # pylint:disable=exec-used - - def test_called_from_function(self): - import warnings - from zope.interface.declarations import classProvides - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - globs = {'classProvides': classProvides, 'IFoo': IFoo} - locs = {} - CODE = "\n".join( - 'def foo():', - ' classProvides(IFoo)' - ) - exec(CODE, globs, locs) - foo = locs'foo' - with warnings.catch_warnings(record=True) as log: - warnings.resetwarnings() - self.assertRaises(TypeError, foo) - if not PYTHON3: - self.assertEqual(len(log), 0) # no longer warn - - def test_called_twice_from_class(self): - import warnings - from zope.interface.declarations import classProvides - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - IBar = InterfaceClass("IBar") - globs = {'classProvides': classProvides, 'IFoo': IFoo, 'IBar': IBar} - locs = {} - CODE = "\n".join( - 'class Foo(object):', - ' classProvides(IFoo)', - ' classProvides(IBar)', - ) - with warnings.catch_warnings(record=True) as log: - warnings.resetwarnings() - try: - exec(CODE, globs, locs) - except TypeError: - if not PYTHON3: - self.assertEqual(len(log), 0) # no longer warn - else: - self.fail("Didn't raise TypeError") - - def test_called_once_from_class(self): - from zope.interface.declarations import classProvides - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - globs = {'classProvides': classProvides, 'IFoo': IFoo} - locs = {} - CODE = "\n".join( - 'class Foo(object):', - ' classProvides(IFoo)', - ) - if self._run_generated_code(CODE, globs, locs): - Foo = locs'Foo' - spec = Foo.__providedBy__ - self.assertEqual(list(spec), IFoo) - -# Test _classProvides_advice through classProvides, its only caller. - - class Test_provider(unittest.TestCase): def _getTargetClass(self): @@ -2090,7 +1870,7 @@ from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") @self._makeOne(IFoo) - class Foo(object): + class Foo: pass self.assertIsInstance(Foo.__provides__, ClassProvides) # pylint:disable=no-member self.assertEqual(list(Foo.__provides__), IFoo) # pylint:disable=no-member @@ -2170,7 +1950,7 @@ def test_wo_existing_provides_classless(self): the_dict = {} - class Foo(object): + class Foo: def __getattribute__(self, name): # Emulate object w/o any class if name == '__class__': @@ -2206,7 +1986,7 @@ from zope.interface.declarations import directlyProvides from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass foo = Foo() directlyProvides(foo, IFoo) @@ -2218,14 +1998,14 @@ from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() spec = self._callFUT(foo) self.assertEqual(list(spec), IFoo) def test_wo_provides_on_class_wo_implements(self): - class Foo(object): + class Foo: pass foo = Foo() spec = self._callFUT(foo) @@ -2242,7 +2022,7 @@ # isinstance(ob.__provides__, SpecificationBase) is not # protected inside any kind of block. - class Foo(object): + class Foo: __provides__ = MissingSomeAttrs(AttributeError) # isinstance() ignores AttributeError on __class__ @@ -2251,18 +2031,14 @@ def test_raises_AttributeError_when_provides_fails_type_check_RuntimeError(self): # isinstance(ob.__provides__, SpecificationBase) is not # protected inside any kind of block. - class Foo(object): + class Foo: __provides__ = MissingSomeAttrs(RuntimeError) - if PYTHON3: - with self.assertRaises(RuntimeError) as exc: - self._callFUT(Foo()) - - self.assertEqual('__class__', exc.exception.args0) - else: - # Python 2 catches everything. + with self.assertRaises(RuntimeError) as exc: self._callFUT(Foo()) + self.assertEqual('__class__', exc.exception.args0) + class Test_getObjectSpecification(Test_getObjectSpecificationFallback, OptimizationTestMixin): @@ -2286,7 +2062,7 @@ return self._getTargetClass()(*args, **kw) def test_wo_providedBy_on_class_wo_implements(self): - class Foo(object): + class Foo: pass foo = Foo() spec = self._callFUT(foo) @@ -2296,7 +2072,7 @@ from zope.interface.declarations import Provides from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass foo = Foo() foo.__providedBy__ = Provides(Foo, IFoo) @@ -2304,7 +2080,7 @@ self.assertEqual(list(spec), IFoo) def test_w_providedBy_invalid_spec(self): - class Foo(object): + class Foo: pass foo = Foo() foo.__providedBy__ = object() @@ -2316,7 +2092,7 @@ from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() foo.__providedBy__ = object() @@ -2324,7 +2100,7 @@ self.assertEqual(list(spec), IFoo) def test_w_providedBy_invalid_spec_w_provides_no_provides_on_class(self): - class Foo(object): + class Foo: pass foo = Foo() foo.__providedBy__ = object() @@ -2333,7 +2109,7 @@ self.assertTrue(spec is expected) def test_w_providedBy_invalid_spec_w_provides_diff_provides_on_class(self): - class Foo(object): + class Foo: pass foo = Foo() foo.__providedBy__ = object() @@ -2347,7 +2123,7 @@ from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() foo.__providedBy__ = object() @@ -2366,7 +2142,7 @@ pass @implementer(IBase) - class Base(object): + class Base: pass @implementer(IDerived) @@ -2391,7 +2167,7 @@ class IDerived(IBase): pass - class Base(object): + class Base: pass @implementer(IDerived) @@ -2415,7 +2191,7 @@ pass @implementer(IDerived) - class Derived(object): + class Derived: pass derived = Derived() @@ -2438,7 +2214,7 @@ pass @implementer(IBase) - class Base(object): + class Base: pass class Derived(Base): @@ -2475,7 +2251,7 @@ pass @implementer(IBase) - class Base(object): + class Base: pass @implementer(IM1) @@ -2512,9 +2288,8 @@ def test_catches_only_AttributeError_on_class(self): # isinstance() tries to get the __class__, which is non-obvious, # so it must be protected too. - PY3 = str is not bytes - MissingSomeAttrs.test_raises(self, self._callFUT, - expected_missing='__class__' if PY3 else '__providedBy__') + MissingSomeAttrs.test_raises( + self, self._callFUT, expected_missing='__class__') @@ -2544,7 +2319,7 @@ from zope.interface.declarations import Provides from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass Foo.__provides__ = Provides(Foo, IFoo) Foo.__providedBy__ = self._makeOne() @@ -2557,7 +2332,7 @@ IFoo = InterfaceClass("IFoo") IBar = InterfaceClass("IBar") @implementer(IFoo) - class Foo(object): + class Foo: pass Foo.__provides__ = Provides(Foo, IBar) Foo.__providedBy__ = self._makeOne() @@ -2573,7 +2348,7 @@ IBar = InterfaceClass("IBar") IBaz = InterfaceClass("IBaz") @implementer(IFoo) - class Foo(object): + class Foo: pass Foo.__provides__ = Provides(Foo, IBar) Foo.__providedBy__ = self._makeOne() @@ -2586,7 +2361,7 @@ class MyException(Exception): pass - class Foo(object): + class Foo: __providedBy__ = self._makeOne() @property @@ -2602,7 +2377,7 @@ class MyException(Exception): pass - class Foo(object): + class Foo: __providedBy__ = self._makeOne() @property @@ -2621,7 +2396,7 @@ pass @implementer(IFoo) - class Foo(object): + class Foo: @property def __provides__(self): @@ -2645,7 +2420,7 @@ # Test _normalizeargs through its callers. -class _Monkey(object): +class _Monkey: # context-manager for replacing module names in the scope of a test. def __init__(self, module, **kw): self.module = module @@ -2661,7 +2436,7 @@ setattr(self.module, key, value) -class _MonkeyDict(object): +class _MonkeyDict: # context-manager for restoring a dict w/in a module in the scope of a test. def __init__(self, module, attrname, **kw): self.module = module
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/tests/test_exceptions.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/tests/test_exceptions.py
Changed
@@ -82,7 +82,7 @@ This is a global function with a simple argument list. It exists to be able to report the same information when - formatting signatures under Python 2 and Python 3. + formatting signatures. """
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/tests/test_interface.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/tests/test_interface.py
Changed
@@ -23,7 +23,6 @@ # pylint:disable=no-value-for-parameter import unittest -from zope.interface._compat import _skip_under_py3k from zope.interface.tests import MissingSomeAttrs from zope.interface.tests import OptimizationTestMixin from zope.interface.tests import CleanUp @@ -40,7 +39,7 @@ def _check(*args, **kw): raise NotImplementedError() - class Foo(object): + class Foo: invariant(_check) self.assertEqual(getattr(Foo, TAGGED_DATA, None), @@ -56,7 +55,7 @@ def _another_check(*args, **kw): raise NotImplementedError() - class Foo(object): + class Foo: invariant(_check) invariant(_another_check) @@ -70,7 +69,7 @@ from zope.interface.interface import taggedValue from zope.interface.interface import TAGGED_DATA - class Foo(object): + class Foo: taggedValue('bar', 'baz') self.assertEqual(getattr(Foo, TAGGED_DATA, None), @@ -80,7 +79,7 @@ from zope.interface.interface import taggedValue from zope.interface.interface import TAGGED_DATA - class Foo(object): + class Foo: taggedValue('bar', 'baz') taggedValue('qux', 'spam') @@ -91,7 +90,7 @@ from zope.interface.interface import taggedValue from zope.interface.interface import TAGGED_DATA - class Foo(object): + class Foo: taggedValue('bar', 'baz') taggedValue('qux', 'spam') taggedValue('bar', 'frob') @@ -238,7 +237,7 @@ def test_implementedBy_hit(self): from zope.interface import interface sb = self._makeOne() - class _Decl(object): + class _Decl: _implied = {sb: {},} def _implementedBy(obj): return _Decl() @@ -248,7 +247,7 @@ def test_providedBy_hit(self): from zope.interface import interface sb = self._makeOne() - class _Decl(object): + class _Decl: _implied = {sb: {},} def _providedBy(obj): return _Decl() @@ -273,7 +272,7 @@ # If either the __name__ or __module__ attribute # is missing from the other object, then we return # NotImplemented. - class RaisesErrorOnMissing(object): + class RaisesErrorOnMissing: Exc = AttributeError def __getattribute__(self, name): try: @@ -319,7 +318,7 @@ self.assertIs(meth(AllowsAnyComparison()), NotImplemented) # If it doesn't have the comparison, Python raises a TypeError. - class AllowsNoComparison(object): + class AllowsNoComparison: __eq__ = None __lt__ = __eq__ __le__ = __eq__ @@ -383,7 +382,7 @@ def test___call___w___conform___returning_value(self): ib = self._makeOne(False) conformed = object() - class _Adapted(object): + class _Adapted: def __conform__(self, iface): return conformed self.assertIs(ib(_Adapted()), conformed) @@ -422,7 +421,7 @@ def test___call___w___conform___miss_ob_provides(self): ib = self._makeOne(True) - class _Adapted(object): + class _Adapted: def __conform__(self, iface): return None adapted = _Adapted() @@ -574,7 +573,7 @@ class IDefaultViewName(Interface): pass - class Context(object): + class Context: pass class RDBModel(Context): @@ -584,7 +583,7 @@ pass @implementer(IOther) - class OtherBase(object): + class OtherBase: pass class Model(OtherBase, Context): @@ -1035,8 +1034,8 @@ def test___hash___normal(self): iface = self._makeOne('HashMe') self.assertEqual(hash(iface), - hash((('HashMe', - 'zope.interface.tests.test_interface')))) + hash(('HashMe', + 'zope.interface.tests.test_interface'))) def test___hash___missing_required_attrs(self): class Derived(self._getTargetClass()): @@ -1143,9 +1142,7 @@ def test__module__is_readonly(self): inst = self._makeOne() - with self.assertRaises((AttributeError, TypeError)): - # CPython 2.7 raises TypeError. Everything else - # raises AttributeError. + with self.assertRaises(AttributeError): inst.__module__ = 'different.module' @@ -1184,7 +1181,7 @@ class IOther(Interface): pass - class Current(object): + class Current: __implemented__ = ICurrent def method1(self, a, b): raise NotImplementedError() @@ -1235,7 +1232,7 @@ class IDerived(IBase): pass - class Current(object): + class Current: __implemented__ = IDerived def method(self): raise NotImplementedError() @@ -1263,13 +1260,13 @@ class IRight(ILeft): pass - class Left(object): + class Left: __implemented__ = ILeft def method(self): raise NotImplementedError() - class Right(object): + class Right: __implemented__ = IRight class Ambi(Left, Right): @@ -1306,10 +1303,10 @@ def method(self): raise NotImplementedError() - class Right(object): + class Right: __implemented__ = IRight - class Other(object): + class Other: __implemented__ = IOther class Mixed(Left, Right): @@ -1351,12 +1348,12 @@ class ICheckMe(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "A method" - class CheckMe(object): + class CheckMe: __implemented__ = ICheckMe attr = 'value' @@ -1372,12 +1369,12 @@ class ICheckMe(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "A method" - class CheckMe(object): + class CheckMe: __implemented__ = ICheckMe attr = 'value' @@ -1402,7 +1399,7 @@ class ISimple(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): """docstring""" @@ -1415,13 +1412,13 @@ class IBase(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): """docstring""" class IDerived(IBase): - attr2 = Attribute(u'My attr2') + attr2 = Attribute('My attr2') def method(): """docstring""" @@ -1441,7 +1438,7 @@ class ISimple(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" @@ -1465,13 +1462,13 @@ class IBase(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" class IDerived(IBase): - attr2 = Attribute(u'My attr2') + attr2 = Attribute('My attr2') def method(): "My method, overridden" @@ -1530,7 +1527,7 @@ class ISimple(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" @@ -1552,13 +1549,13 @@ class IBase(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" class IDerived(IBase): - attr2 = Attribute(u'My attr2') + attr2 = Attribute('My attr2') def method(): "My method, overridden" @@ -1601,7 +1598,7 @@ class ISimple(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" @@ -1623,13 +1620,13 @@ class IBase(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" class IDerived(IBase): - attr2 = Attribute(u'My attr2') + attr2 = Attribute('My attr2') def method(): "My method, overridden" @@ -1671,7 +1668,7 @@ class ISimple(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" @@ -1685,13 +1682,13 @@ class IBase(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" class IDerived(IBase): - attr2 = Attribute(u'My attr2') + attr2 = Attribute('My attr2') def method(): "My method, overridden" @@ -1718,7 +1715,7 @@ class ISimple(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" @@ -1731,13 +1728,13 @@ class IBase(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" class IDerived(IBase): - attr2 = Attribute(u'My attr2') + attr2 = Attribute('My attr2') def method(): "My method, overridden" @@ -1806,7 +1803,7 @@ bar = Attribute('bar; must eval to Boolean True if foo does') invariant(_ifFooThenBar) - class HasInvariant(object): + class HasInvariant: pass # set up @@ -1839,7 +1836,7 @@ class ISubInvariant(IInvariant): invariant(_barGreaterThanFoo) - class HasInvariant(object): + class HasInvariant: pass # nested interfaces with invariants: @@ -1883,7 +1880,7 @@ bar = Attribute('bar; must eval to Boolean True if foo does') invariant(_ifFooThenBar) - class HasInvariant(object): + class HasInvariant: pass # now we'll do two invariants on the same interface, @@ -1942,21 +1939,6 @@ self.assertEqual(IDocstringAndAttribute.__doc__, "") self.assertEqual(list(IDocstringAndAttribute), '__doc__') - @_skip_under_py3k - def testIssue228(self): - # Test for http://collector.zope.org/Zope3-dev/228 - # Old style classes don't have a '__class__' attribute - # No old style classes in Python 3, so the test becomes moot. - from zope.interface import Interface - - class I(Interface): - "xxx" - - class OldStyle: - __providedBy__ = None - - self.assertRaises(AttributeError, I.providedBy, OldStyle) - def test_invariant_as_decorator(self): from zope.interface import Interface from zope.interface import Attribute @@ -1974,7 +1956,7 @@ raise Invalid('max < min') @implementer(IRange) - class Range(object): + class Range: def __init__(self, min, max): self.min, self.max = min, max @@ -2009,7 +1991,7 @@ self.assertEqual(IDerived2.getTaggedValue('qux'), 'Spam Spam') self.assertEqual(IDerived2.getTaggedValue('foo'), 'bar') - self.assertEqual(set(IDerived2.getTaggedValueTags()), set('qux', 'foo')) + self.assertEqual(set(IDerived2.getTaggedValueTags()), {'qux', 'foo'}) def _make_taggedValue_tree(self, base): from zope.interface import taggedValue @@ -2106,7 +2088,7 @@ pass @implementer(I) - class C(object): + class C: def __conform__(self, proto): return 0 @@ -2120,7 +2102,7 @@ pass @implementer(I) - class C(object): + class C: pass c = C() @@ -2132,7 +2114,7 @@ class I(Interface): pass - class C(object): + class C: pass c = C() @@ -2144,7 +2126,7 @@ class I(Interface): pass - class C(object): + class C: pass c = C() @@ -2163,7 +2145,7 @@ class I(Interface): pass - class C(object): + class C: pass c = C() @@ -2187,7 +2169,7 @@ return 42 @implementer(I) - class O(object): + class O: pass self.assertEqual(42, I(object())) @@ -2211,12 +2193,12 @@ """Nothing special.""" @implementer(IAdapt) - class Conform24(object): + class Conform24: def __conform__(self, iface): return 24 @implementer(IAdapt) - class ConformNone(object): + class ConformNone: def __conform__(self, iface): return None @@ -2243,14 +2225,10 @@ def __adapt__(self, obj): if not self.providedBy(obj): return 42 - if sys.version_info:2 > (3, 5): - # Python 3.5 raises 'RuntimeError: super() __class__ is not a type' - return super().__adapt__(obj) - - return super(type(I), self).__adapt__(obj) + return super().__adapt__(obj) @implementer(I) - class O(object): + class O: pass self.assertEqual(42, I(object())) @@ -2575,7 +2553,7 @@ return fromMethod(*args, **kw) def test_no_args(self): - class Foo(object): + class Foo: def bar(self): "DOCSTRING" method = self._callFUT(Foo.bar) @@ -2591,7 +2569,7 @@ self.assertEqual(info'kwargs', None) def test_full_spectrum(self): - class Foo(object): + class Foo: def bar(self, foo, bar='baz', *args, **kw): # pylint:disable=keyword-arg-before-vararg "DOCSTRING" method = self._callFUT(Foo.bar) @@ -2617,7 +2595,7 @@ self.assertEqual(info'varargs', None) self.assertEqual(info'kwargs', None) -class DummyDependent(object): +class DummyDependent: def __init__(self): self._changed = @@ -2644,7 +2622,7 @@ raise Invalid('If Foo, then Bar!') -class _Monkey(object): +class _Monkey: # context-manager for replacing module names in the scope of a test. def __init__(self, module, **kw): self.module = module
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/tests/test_interfaces.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/tests/test_interfaces.py
Changed
@@ -1,7 +1,7 @@ import unittest -class _ConformsToIObjectEvent(object): +class _ConformsToIObjectEvent: def _makeOne(self, target=None): if target is None:
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/tests/test_odd_declarations.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/tests/test_odd_declarations.py
Changed
@@ -27,7 +27,6 @@ from zope.interface import classImplements from zope.interface import classImplementsOnly from zope.interface import implementedBy -from zope.interface._compat import _skip_under_py3k class I1(Interface): pass class I2(Interface): pass @@ -36,7 +35,7 @@ class I4(Interface): pass class I5(Interface): pass -class Odd(object): +class Odd: pass Odd = odd.MetaClass('Odd', Odd.__bases__, {}) @@ -186,10 +185,6 @@ directlyProvides(ob, directlyProvidedBy(ob), I2) self.assertTrue(I2 in providedBy(ob)) - @_skip_under_py3k - def test_directlyProvides_fails_for_odd_class(self): - self.assertRaises(TypeError, directlyProvides, C, I5) - # see above #def TODO_test_classProvides_fails_for_odd_class(self): # try: @@ -222,12 +217,12 @@ # This is used for testing support for ExtensionClass in new interfaces. - class A(object): + class A: a = 1 A = odd.MetaClass('A', A.__bases__, A.__dict__) - class B(object): + class B: b = 1 B = odd.MetaClass('B', B.__bases__, B.__dict__) @@ -257,12 +252,4 @@ self.assertEqual(c.c, 1) c.c - try: - from types import ClassType - except ImportError: - pass - else: - # This test only makes sense under Python 2.x - assert not isinstance(C, (type, ClassType)) - self.assertIs(C.__class__.__class__, C.__class__)
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/tests/test_registry.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/tests/test_registry.py
Changed
@@ -83,16 +83,16 @@ pass ifoo = IFoo('IFoo') - @named(u'foo') - class Foo(object): + @named('foo') + class Foo: pass foo = Foo() - _info = u'info' + _info = 'info' comp = self._makeOne() comp.registerUtility(foo, ifoo, info=_info) self.assertEqual( - comp._utility_registrationsifoo, u'foo', + comp._utility_registrationsifoo, 'foo', (foo, _info, None)) def test_registerUtility_both_factory_and_component(self): @@ -111,8 +111,8 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' _to_reg = object() comp = self._makeOne() _monkey, _events = self._wrapEvents() @@ -143,8 +143,8 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' _to_reg = object() def _factory(): return _to_reg @@ -166,11 +166,11 @@ self.assertTrue(event.object.factory is _factory) def test_registerUtility_no_provided_available(self): - class Foo(object): + class Foo: pass - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' _to_reg = Foo() comp = self._makeOne() self.assertRaises(TypeError, @@ -184,11 +184,11 @@ class IFoo(InterfaceClass): pass - class Foo(object): + class Foo: pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' _to_reg = Foo() directlyProvides(_to_reg, ifoo) comp = self._makeOne() @@ -214,8 +214,8 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name, _info) @@ -230,9 +230,9 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info1 = u'info1' - _info2 = u'info2' - _name = u'name' + _info1 = 'info1' + _info2 = 'info2' + _name = 'name' _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name, _info1) @@ -242,7 +242,7 @@ self.assertEqual(len(_events), 2) # unreg, reg self.assertEqual(comp._utility_registrations(ifoo, _name), (_to_reg, _info2, None)) # replaced - self.assertEqual(comp.utilities._subscribers0ifoou'', + self.assertEqual(comp.utilities._subscribers0ifoo'', (_to_reg,)) def test_registerUtility_w_different_names_same_component(self): @@ -251,9 +251,9 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' _other_reg = object() _to_reg = object() comp = self._makeOne() @@ -266,7 +266,7 @@ (_other_reg, _info, None)) self.assertEqual(comp._utility_registrations(ifoo, _name2), (_to_reg, _info, None)) - self.assertEqual(comp.utilities._subscribers0ifoou'', + self.assertEqual(comp.utilities._subscribers0ifoo'', (_other_reg, _to_reg,)) def test_registerUtility_replaces_existing_reg(self): @@ -278,8 +278,8 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' _before, _after = object(), object() comp = self._makeOne() comp.registerUtility(_before, ifoo, _name, _info) @@ -316,9 +316,9 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) @@ -333,8 +333,8 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' _to_reg = object() comp = self._makeOne() _monkey, _events = self._wrapEvents() @@ -349,7 +349,7 @@ reg_count = 0 def registerUtility(self, *args): self.reg_count += 1 - super(CompThatChangesAfter1Reg, self).registerUtility(*args) + super().registerUtility(*args) if self.reg_count == 1: self._utility_registrations = dict(self._utility_registrations) @@ -374,7 +374,7 @@ if self.reg_count == 2: self._utility_registrations = dict(self._utility_registrations) - super(CompThatChangesAfter2Reg, self).registerUtility(*args) + super().registerUtility(*args) comp = CompThatChangesAfter2Reg() comp.registerUtility(object(), Interface) @@ -414,7 +414,7 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _name = u'name' + _name = 'name' _to_reg = object() comp = self._makeOne() _monkey, _events = self._wrapEvents() @@ -431,7 +431,7 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _name = u'name' + _name = 'name' _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name) @@ -462,8 +462,8 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' _to_reg = object() def _factory(): return _to_reg @@ -493,11 +493,11 @@ class IFoo(InterfaceClass): pass - class Foo(object): + class Foo: pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' _to_reg = Foo() directlyProvides(_to_reg, ifoo) comp = self._makeOne() @@ -527,11 +527,11 @@ class IFoo(InterfaceClass): pass - class Foo(object): + class Foo: pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' _to_reg = Foo() directlyProvides(_to_reg, ifoo) comp = self._makeOne() @@ -560,9 +560,9 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) @@ -578,9 +578,9 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' _to_reg = dict() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) @@ -599,9 +599,9 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' _to_reg = dict() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) @@ -620,9 +620,9 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' _to_reg = dict() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) @@ -645,9 +645,9 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' _other_reg = object() _to_reg = object() comp = self._makeOne() @@ -665,9 +665,9 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' # First register something hashable _other_reg = object() # Then it transfers to something unhashable @@ -692,9 +692,9 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) @@ -776,8 +776,8 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _name1 = u'name1' - _name2 = u'name2' + _name1 = 'name1' + _name2 = 'name2' _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, name=_name1) @@ -799,8 +799,8 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _name1 = u'name1' - _name2 = u'name2' + _name1 = 'name1' + _name2 = 'name2' _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, name=_name1) @@ -817,16 +817,16 @@ ifoo = IFoo('IFoo') ibar = IFoo('IBar') - @named(u'foo') - class Foo(object): + @named('foo') + class Foo: pass - _info = u'info' + _info = 'info' comp = self._makeOne() comp.registerAdapter(Foo, (ibar,), ifoo, info=_info) self.assertEqual( - comp._adapter_registrations(ibar,), ifoo, u'foo', + comp._adapter_registrations(ibar,), ifoo, 'foo', (Foo, _info)) def test_registerAdapter_w_explicit_provided_and_required(self): @@ -838,8 +838,8 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' def _factory(context): raise NotImplementedError() @@ -871,10 +871,10 @@ pass ibar = IFoo('IBar') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -891,12 +891,12 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' _to_reg = object() @implementer(ifoo) - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -927,9 +927,9 @@ pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' - class _Factory(object): + _info = 'info' + _name = 'name' + class _Factory: pass comp = self._makeOne() @@ -943,9 +943,9 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _name = u'name' - class _Factory(object): + _info = 'info' + _name = 'name' + class _Factory: pass comp = self._makeOne() self.assertRaises(TypeError, comp.registerAdapter, _Factory, @@ -960,9 +960,9 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' - class _Factory(object): + _info = 'info' + _name = 'name' + class _Factory: pass comp = self._makeOne() _monkey, _events = self._wrapEvents() @@ -997,13 +997,13 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _name = u'name' - class _Factory(object): + _info = 'info' + _name = 'name' + class _Factory: pass @implementer(ibar) - class _Context(object): + class _Context: pass _ctx_impl = implementedBy(_Context) comp = self._makeOne() @@ -1035,9 +1035,9 @@ pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' - class _Factory(object): + _info = 'info' + _name = 'name' + class _Factory: pass comp = self._makeOne() self.assertRaises(TypeError, comp.registerAdapter, _Factory, object(), @@ -1052,9 +1052,9 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _name = u'name' - class _Factory(object): + _info = 'info' + _name = 'name' + class _Factory: __component_adapts__ = (ibar,) comp = self._makeOne() @@ -1086,8 +1086,8 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' def _factory(context): raise NotImplementedError() @@ -1118,7 +1118,7 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -1135,7 +1135,7 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -1169,7 +1169,7 @@ ifoo = IFoo('IFoo') ibar = IFoo('IBar') @implementer(ifoo) - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -1199,7 +1199,7 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: __component_adapts__ = (ibar,) comp = self._makeOne() @@ -1233,10 +1233,10 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' - class _Factory(object): + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' + class _Factory: pass comp = self._makeOne() @@ -1286,11 +1286,11 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: def __init__(self, context): self.context = context @implementer(ibar) - class _Context(object): + class _Context: pass _context = _Context() comp = self._makeOne() @@ -1308,7 +1308,7 @@ ifoo = IFoo('IFoo') ibar = IFoo('IBar') @implementer(ibar) - class _Context(object): + class _Context: pass _context = _Context() comp = self._makeOne() @@ -1322,11 +1322,11 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: def __init__(self, context): self.context = context @implementer(ibar) - class _Context(object): + class _Context: pass _context = _Context() comp = self._makeOne() @@ -1349,18 +1349,18 @@ pass @implementer(IBase) - class Base(object): + class Base: pass @implementer(IDerived) class Derived(Base): pass - class AdapterBase(object): + class AdapterBase: def __init__(self, context): self.context = context - class AdapterDerived(object): + class AdapterDerived: def __init__(self, context): self.context = context @@ -1392,7 +1392,7 @@ class IFoo(Interface): pass - class Base(object): + class Base: pass class Child1(Base): @@ -1406,11 +1406,11 @@ class Derived(Child1, Child2): pass - class AdapterBase(object): + class AdapterBase: def __init__(self, context): self.context = context - class AdapterDerived(object): + class AdapterDerived: def __init__(self, context): self.context = context @@ -1438,10 +1438,10 @@ ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() @@ -1458,10 +1458,10 @@ ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() @@ -1480,14 +1480,14 @@ ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() - class _Factory(object): + class _Factory: def __init__(self, context1, context2): self.context = context1, context2 comp = self._makeOne() @@ -1506,10 +1506,10 @@ ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() @@ -1526,14 +1526,14 @@ ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() - class _Factory(object): + class _Factory: def __init__(self, context1, context2): self.context = context1, context2 comp = self._makeOne() @@ -1566,14 +1566,14 @@ pass @implementer(IBase) - class Base(object): + class Base: pass @implementer(IDerived) class Derived(Base): pass - class AdapterBase(object): + class AdapterBase: def __init__(self, context1, context2): self.context1 = context1 self.context2 = context2 @@ -1608,10 +1608,10 @@ ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() @@ -1628,10 +1628,10 @@ ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() @@ -1655,21 +1655,21 @@ ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() - class _Factory1(object): + class _Factory1: def __init__(self, context1, context2): self.context = context1, context2 - class _Factory2(object): + class _Factory2: def __init__(self, context1, context2): self.context = context1, context2 - _name1 = u'name1' - _name2 = u'name2' + _name1 = 'name1' + _name2 = 'name2' comp = self._makeOne() comp.registerAdapter(_Factory1, (ibar, ibaz), ifoo, name=_name1) comp.registerAdapter(_Factory2, (ibar, ibaz), ifoo, name=_name2) @@ -1687,8 +1687,8 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _name = u'name' - _info = u'info' + _name = 'name' + _info = 'info' def _factory(context): raise NotImplementedError() @@ -1705,8 +1705,8 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _blank = u'' - _info = u'info' + _blank = '' + _info = 'info' def _factory(context): raise NotImplementedError() comp = self._makeOne() @@ -1742,11 +1742,11 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _blank = u'' + _info = 'info' + _blank = '' @implementer(ifoo) - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -1780,9 +1780,9 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _blank = u'' - class _Factory(object): + _info = 'info' + _blank = '' + class _Factory: __component_adapts__ = (ibar,) comp = self._makeOne() @@ -1815,8 +1815,8 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _blank = u'' - _info = u'info' + _blank = '' + _info = 'info' def _factory(context): raise NotImplementedError() @@ -1840,9 +1840,9 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IFoo') - _info = u'info' - _blank = u'' - class _Factory(object): + _info = 'info' + _blank = '' + class _Factory: pass comp = self._makeOne() @@ -1872,7 +1872,7 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _nonblank = u'nonblank' + _nonblank = 'nonblank' comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterSubscriptionAdapter, required=ifoo, provided=ibar, name=_nonblank) @@ -1897,7 +1897,7 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -1915,7 +1915,7 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -1947,7 +1947,7 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -1981,7 +1981,7 @@ ifoo = IFoo('IFoo') ibar = IFoo('IBar') @implementer(ifoo) - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -2011,7 +2011,7 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: __component_adapts__ = (ibar,) comp = self._makeOne() @@ -2042,7 +2042,7 @@ ibar = IFoo('IBar') comp = self._makeOne() @implementer(ibar) - class Bar(object): + class Bar: pass bar = Bar() self.assertEqual(list(comp.subscribers((bar,), ifoo)), ) @@ -2054,7 +2054,7 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: __component_adapts__ = (ibar,) def __init__(self, context): self._context = context @@ -2064,7 +2064,7 @@ comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo) comp.registerSubscriptionAdapter(_Derived, (ibar,), ifoo) @implementer(ibar) - class Bar(object): + class Bar: pass bar = Bar() subscribers = comp.subscribers((bar,), ifoo) @@ -2081,7 +2081,7 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _nonblank = u'nonblank' + _nonblank = 'nonblank' comp = self._makeOne() def _factory(context): raise NotImplementedError() @@ -2097,8 +2097,8 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _blank = u'' - _info = u'info' + _blank = '' + _info = 'info' def _factory(context): raise NotImplementedError() @@ -2129,9 +2129,9 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _blank = u'' - class _Factory(object): + _info = 'info' + _blank = '' + class _Factory: __component_adapts__ = (ifoo,) pass @@ -2184,7 +2184,7 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _nonblank = u'nonblank' + _nonblank = 'nonblank' comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterHandler, required=(ifoo,), name=_nonblank) @@ -2263,7 +2263,7 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - class _Factory(object): + class _Factory: __component_adapts__ = (ifoo,) comp = self._makeOne() @@ -2292,7 +2292,7 @@ ifoo = IFoo('IFoo') comp = self._makeOne() @implementer(ifoo) - class Bar(object): + class Bar: pass bar = Bar() comp.handle((bar,)) # doesn't raise @@ -2313,7 +2313,7 @@ comp.registerHandler(_factory_1, (ifoo,)) comp.registerHandler(_factory_2, (ifoo,)) @implementer(ifoo) - class Bar(object): + class Bar: pass bar = Bar() comp.handle(bar) @@ -2355,13 +2355,13 @@ class IFoo(Interface): "Does nothing" - class UtilityImplementingFoo(object): + class UtilityImplementingFoo: "Does nothing" comps = self._makeOne() for i in range(30): - comps.registerUtility(UtilityImplementingFoo(), IFoo, name=u'%s' % (i,)) + comps.registerUtility(UtilityImplementingFoo(), IFoo, name='{}'.format(i)) orig_generation = comps.utilities._generation @@ -2374,14 +2374,14 @@ self.assertEqual(len(orig_subscribers), 1) self.assertEqual(len(orig_subscribers0), 1) self.assertEqual(len(orig_subscribers0IFoo), 1) - self.assertEqual(len(orig_subscribers0IFoou''), 30) + self.assertEqual(len(orig_subscribers0IFoo''), 30) # Blow a bunch of them away, creating artificial corruption new_adapters = comps.utilities._adapters = type(orig_adapters)() new_adapters.append({}) d = new_adapters0IFoo = {} for name in range(10): - name = type(u'')(str(name)) + name = str(str(name)) dname = orig_adapters0IFooname self.assertNotEqual(orig_adapters, new_adapters) @@ -2389,12 +2389,12 @@ new_subscribers = comps.utilities._subscribers = type(orig_subscribers)() new_subscribers.append({}) d = new_subscribers0IFoo = {} - du'' = () + d'' = () for name in range(5, 12): # 12 - 5 = 7 - name = type(u'')(str(name)) + name = str(str(name)) comp = orig_adapters0IFooname - du'' += (comp,) + d'' += (comp,) # We can preflight (by default) and nothing changes rebuild_results_preflight = comps.rebuildUtilityRegistryFromLocalCache() @@ -2417,11 +2417,11 @@ self.assertEqual(rebuild_results_preflight, rebuild_results) self.assertEqual(new_adapters, orig_adapters) self.assertEqual( - len(new_subscribers0IFoou''), - len(orig_subscribers0IFoou'')) + len(new_subscribers0IFoo''), + len(orig_subscribers0IFoo'')) - for orig_subscriber in orig_subscribers0IFoou'': - self.assertIn(orig_subscriber, new_subscribers0IFoou'') + for orig_subscriber in orig_subscribers0IFoo'': + self.assertIn(orig_subscriber, new_subscribers0IFoo'') # Preflighting, rebuilding again produce no changes. preflight_after = comps.rebuildUtilityRegistryFromLocalCache() @@ -2464,11 +2464,11 @@ pass ifoo = InterfaceClassSubclass('IFoo') - class _Registry(object): + class _Registry: def __repr__(self): return '_REGISTRY' registry = _Registry() - name = u'name' + name = 'name' doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, ifoo, name, component, doc, factory), @@ -2488,7 +2488,7 @@ verifyObject(IUtilityRegistration, ur) def test___repr__(self): - class _Component(object): + class _Component: __name__ = 'TEST' _component = _Component() ur, _registry, _name = self._makeOne(_component) @@ -2497,7 +2497,7 @@ % (_name)) def test___repr___provided_wo_name(self): - class _Component(object): + class _Component: def __repr__(self): return 'TEST' _component = _Component() @@ -2508,7 +2508,7 @@ % (_name)) def test___repr___component_wo_name(self): - class _Component(object): + class _Component: def __repr__(self): return 'TEST' _component = _Component() @@ -2650,11 +2650,11 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Registry(object): + class _Registry: def __repr__(self): return '_REGISTRY' registry = _Registry() - name = u'name' + name = 'name' doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, (ibar,), ifoo, name, component, doc), @@ -2674,7 +2674,7 @@ verifyObject(IAdapterRegistration, ar) def test___repr__(self): - class _Component(object): + class _Component: __name__ = 'TEST' _component = _Component() ar, _registry, _name = self._makeOne(_component) @@ -2683,7 +2683,7 @@ + "'DOCSTRING')") % (_name)) def test___repr___provided_wo_name(self): - class _Component(object): + class _Component: def __repr__(self): return 'TEST' _component = _Component() @@ -2694,7 +2694,7 @@ + "'DOCSTRING')") % (_name)) def test___repr___component_wo_name(self): - class _Component(object): + class _Component: def __repr__(self): return 'TEST' _component = _Component() @@ -2859,11 +2859,11 @@ pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Registry(object): + class _Registry: def __repr__(self): # pragma: no cover return '_REGISTRY' registry = _Registry() - name = u'name' + name = 'name' doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, (ibar,), ifoo, name, component, doc), @@ -2895,11 +2895,11 @@ class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - class _Registry(object): + class _Registry: def __repr__(self): return '_REGISTRY' registry = _Registry() - name = u'name' + name = 'name' doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, (ifoo,), name, component, doc), @@ -2927,7 +2927,7 @@ self.assertTrue(hr.provided is None) def test___repr___factory_w_name(self): - class _Factory(object): + class _Factory: __name__ = 'TEST' hr, _registry, _name = self._makeOne(_Factory()) self.assertEqual(repr(hr), @@ -2935,7 +2935,7 @@ + "'DOCSTRING')") % (_name)) def test___repr___factory_wo_name(self): - class _Factory(object): + class _Factory: def __repr__(self): return 'TEST' hr, _registry, _name = self._makeOne(_Factory()) @@ -3041,11 +3041,11 @@ def _getTargetClass(self): return PersistentComponentsDict -class _Monkey(object): +class _Monkey: # context-manager for replacing module names in the scope of a test. def __init__(self, module, **kw): self.module = module - self.to_restore = dict((key, getattr(module, key)) for key in kw) + self.to_restore = {key: getattr(module, key) for key in kw} for key, value in kw.items(): setattr(module, key, value)
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/tests/test_ro.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/tests/test_ro.py
Changed
@@ -47,26 +47,26 @@ return _legacy_flatten(ob) def test_w_empty_bases(self): - class Foo(object): + class Foo: pass foo = Foo() foo.__bases__ = () self.assertEqual(self._callFUT(foo), foo) def test_w_single_base(self): - class Foo(object): + class Foo: pass self.assertEqual(self._callFUT(Foo), Foo, object) def test_w_bases(self): - class Foo(object): + class Foo: pass class Bar(Foo): pass self.assertEqual(self._callFUT(Bar), Bar, Foo, object) def test_w_diamond(self): - class Foo(object): + class Foo: pass class Bar(Foo): pass @@ -85,26 +85,26 @@ return _legacy_ro(ob, **kwargs) def test_w_empty_bases(self): - class Foo(object): + class Foo: pass foo = Foo() foo.__bases__ = () self.assertEqual(self._callFUT(foo), foo) def test_w_single_base(self): - class Foo(object): + class Foo: pass self.assertEqual(self._callFUT(Foo), Foo, object) def test_w_bases(self): - class Foo(object): + class Foo: pass class Bar(Foo): pass self.assertEqual(self._callFUT(Bar), Bar, Foo, object) def test_w_diamond(self): - class Foo(object): + class Foo: pass class Bar(Foo): pass @@ -117,7 +117,7 @@ def _make_IOErr(self): # This can't be done in the standard C3 ordering. - class Foo(object): + class Foo: def __init__(self, name, *bases): self.__name__ = name self.__bases__ = bases @@ -153,13 +153,13 @@ pass @implementer(IFoo) - class ImplementsFoo(object): + class ImplementsFoo: pass class ExtendsFoo(ImplementsFoo): pass - class ImplementsNothing(object): + class ImplementsNothing: pass class ExtendsFooImplementsNothing(ExtendsFoo, ImplementsNothing): @@ -176,7 +176,7 @@ implementedBy(object)) -class C3Setting(object): +class C3Setting: def __init__(self, setting, value): self._setting = setting @@ -202,7 +202,7 @@ from zope.interface.ro import ro return ro(ob, **kwargs) - def test_complex_diamond(self, base=object): + def _make_complex_diamond(self, base): # https://github.com/zopefoundation/zope.interface/issues/21 O = base class F(O): @@ -223,10 +223,13 @@ return A + def test_complex_diamond_object(self): + self._make_complex_diamond(object) + def test_complex_diamond_interface(self): from zope.interface import Interface - IA = self.test_complex_diamond(Interface) + IA = self._make_complex_diamond(Interface) self.assertEqual( x.__name__ for x in IA.__iro__, @@ -236,7 +239,7 @@ def test_complex_diamond_use_legacy_argument(self): from zope.interface import Interface - A = self.test_complex_diamond(Interface) + A = self._make_complex_diamond(Interface) legacy_A_iro = self._callFUT(A, use_legacy_ro=True) self.assertNotEqual(A.__iro__, legacy_A_iro) @@ -246,7 +249,7 @@ def test_complex_diamond_compare_legacy_argument(self): from zope.interface import Interface - A = self.test_complex_diamond(Interface) + A = self._make_complex_diamond(Interface) computed_A_iro = self._callFUT(A, log_changed_ro=True) # It matches, of course, but we did log a warning. self.assertEqual(tuple(computed_A_iro), A.__iro__) @@ -274,7 +277,7 @@ # See https://github.com/zopefoundation/zope.interface/pull/182#issuecomment-598754056 from zope.interface import ro # pylint:disable=inherit-non-class - class _Based(object): + class _Based: __bases__ = () def __init__(self, name, bases=(), attrs=None): @@ -334,9 +337,6 @@ self._callFUT(ExtendedPathIndex, strict=True) def test_OSError_IOError(self): - if OSError is not IOError: - # Python 2 - self.skipTest("Requires Python 3 IOError == OSError") from zope.interface.common import interfaces from zope.interface import providedBy @@ -364,7 +364,7 @@ warnings.simplefilter('error') with C3Setting(ro.C3.WARN_BAD_IRO, True), C3Setting(ro.C3.STRICT_IRO, False): with self.assertRaises(ro.InconsistentResolutionOrderWarning): - super(Test_c3_ro, self).test_non_orderable() + super().test_non_orderable() IOErr, _ = self._make_IOErr() with self.assertRaises(ro.InconsistentResolutionOrderError): @@ -404,7 +404,7 @@ class Test_ROComparison(unittest.TestCase): - class MockC3(object): + class MockC3: direct_inconsistency = False bases_had_inconsistency = False
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/tests/test_verify.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/tests/test_verify.py
Changed
@@ -43,7 +43,7 @@ class ICurrent(Interface): pass - class Current(object): + class Current: pass self.assertRaises(DoesNotImplement, self._callFUT, ICurrent, Current) @@ -55,7 +55,7 @@ class ICurrent(Interface): pass - class Current(object): + class Current: pass classImplements(Current, ICurrent) @@ -72,7 +72,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: pass self.assertRaises(BrokenImplementation, @@ -87,7 +87,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self): raise NotImplementedError() @@ -107,7 +107,7 @@ pass @implementer(IDerived) - class Current(object): + class Current: pass self.assertRaises(BrokenImplementation, @@ -125,7 +125,7 @@ pass @implementer(IDerived) - class Current(object): + class Current: def method(self): raise NotImplementedError() @@ -143,7 +143,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, b): raise NotImplementedError() @@ -161,7 +161,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self): raise NotImplementedError() @@ -180,7 +180,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self): raise NotImplementedError() @@ -199,7 +199,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self): raise NotImplementedError() @@ -218,7 +218,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a, b): raise NotImplementedError() @@ -236,7 +236,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a, b=None): raise NotImplementedError() @@ -253,7 +253,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, *args): raise NotImplementedError() @@ -271,7 +271,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, **kw): raise NotImplementedError() @@ -289,7 +289,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a, *args): raise NotImplementedError() @@ -306,7 +306,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a, *args, **kw): raise NotImplementedError() @@ -324,7 +324,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a): raise NotImplementedError() @@ -342,7 +342,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a, *args): raise NotImplementedError() @@ -359,7 +359,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, *args): raise NotImplementedError() @@ -376,7 +376,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, **kw): raise NotImplementedError() @@ -394,7 +394,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a, *args): raise NotImplementedError() @@ -414,7 +414,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a): raise NotImplementedError() @@ -494,7 +494,7 @@ def __call__(self, *args, **kw): raise NotImplementedError() - class QuasiCallable(object): + class QuasiCallable: def __call__(self, *args, **kw): raise NotImplementedError() @@ -522,7 +522,7 @@ """docstring""" @implementer(ICurrent) - class Current(object): + class Current: @decorator def method(self, a): @@ -564,7 +564,7 @@ def meth2(arg1): "Method 2" - class SeveralMethods(object): + class SeveralMethods: pass with self.assertRaises(MultipleInvalid) as exc: @@ -642,7 +642,7 @@ "The bar method" @provider(IFoo) - class Foo(object): + class Foo: @staticmethod def bar(a, b):
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/src/zope/interface/verify.py -> _service:tar_scm:zope.interface-6.0.tar.gz/src/zope/interface/verify.py
Changed
@@ -13,14 +13,11 @@ ############################################################################## """Verify interface implementations """ -from __future__ import print_function import inspect import sys from types import FunctionType from types import MethodType -from zope.interface._compat import PYPY2 - from zope.interface.exceptions import BrokenImplementation from zope.interface.exceptions import BrokenMethodImplementation from zope.interface.exceptions import DoesNotImplement @@ -102,7 +99,7 @@ # We can't verify non-methods on classes, since the # class may provide attrs in it's __init__. return - # TODO: On Python 3, this should use ``raise...from`` + # TODO: This should use ``raise...from`` raise BrokenImplementation(iface, desc, candidate) if not isinstance(desc, Method): @@ -124,13 +121,12 @@ return if isinstance(attr, FunctionType): - if sys.version_info0 >= 3 and isinstance(candidate, type) and vtype == 'c': - # This is an "unbound method" in Python 3. + if isinstance(candidate, type) and vtype == 'c': + # This is an "unbound method". # Only unwrap this if we're verifying implementedBy; # otherwise we can unwrap @staticmethod on classes that directly # provide an interface. - meth = fromFunction(attr, iface, name=name, - imlevel=1) + meth = fromFunction(attr, iface, name=name, imlevel=1) else: # Nope, just a normal function meth = fromFunction(attr, iface, name=name) @@ -156,8 +152,6 @@ # the same. mess = _incompat(desc.getSignatureInfo(), meth.getSignatureInfo()) if mess: - if PYPY2 and _pypy2_false_positive(mess, candidate, vtype): - return raise BrokenMethodImplementation(desc, mess, attr, iface, candidate) @@ -174,33 +168,6 @@ verifyObject.__doc__ = _verify.__doc__ _MSG_TOO_MANY = 'implementation requires too many arguments' -_KNOWN_PYPY2_FALSE_POSITIVES = frozenset(( - _MSG_TOO_MANY, -)) - - -def _pypy2_false_positive(msg, candidate, vtype): - # On PyPy2, builtin methods and functions like - # ``dict.pop`` that take pseudo-optional arguments - # (those with no default, something you can't express in Python 2 - # syntax; CPython uses special internal APIs to implement these methods) - # return false failures because PyPy2 doesn't expose any way - # to detect this pseudo-optional status. PyPy3 doesn't have this problem - # because of __defaults_count__, and CPython never gets here because it - # returns true for ``ismethoddescriptor`` or ``isbuiltin``. - # - # We can't catch all such cases, but we can handle the common ones. - # - if msg not in _KNOWN_PYPY2_FALSE_POSITIVES: - return False - - known_builtin_types = vars(__builtins__).values() - candidate_type = candidate if vtype == 'c' else type(candidate) - if candidate_type in known_builtin_types: - return True - - return False - def _incompat(required, implemented): #if (required'positional' !=
View file
_service:tar_scm:zope.interface-5.5.2.tar.gz/tox.ini -> _service:tar_scm:zope.interface-6.0.tar.gz/tox.ini
Changed
@@ -1,32 +1,31 @@ # Generated from: # https://github.com/zopefoundation/meta/tree/master/config/c-code tox -minversion = 3.18 +minversion = 4.0 envlist = lint - py27,py27-pure - py35,py35-pure - py36,py36-pure py37,py37-pure py38,py38-pure py39,py39-pure py310,py310-pure py311,py311-pure - pypy + py312,py312-pure pypy3 docs coverage testenv usedevelop = true +pip_pre = py312: true deps = + Sphinx setenv = pure: PURE_PYTHON=1 - !pure-!pypy-!pypy3: PURE_PYTHON=0 + !pure-!pypy3: PURE_PYTHON=0 ZOPE_INTERFACE_STRICT_IRO=1 commands = coverage run -p -m unittest discover -s src {posargs} - !py27-!pypy: sphinx-build -b doctest -d {envdir}/.cache/doctrees docs {envdir}/.cache/doctest + sphinx-build -b doctest -d {envdir}/.cache/doctrees docs {envdir}/.cache/doctest extras = test docs @@ -44,7 +43,7 @@ coverage combine coverage html -i coverage report -i -m --fail-under=99 -depends = py27,py27-pure,py35,py35-pure,py36,py36-pure,py37,py37-pure,py38,py38-pure,py39,py39-pure,py310,py310-pure,pypy,pypy3,docs +depends = py37,py37-pure,py38,py38-pure,py39,py39-pure,py310,py310-pure,py311,py311-pure,pypy,pypy3,docs parallel_show_output = true testenv:lint
Locations
Projects
Search
Status Monitor
Help
Open Build Service
OBS Manuals
API Documentation
OBS Portal
Reporting a Bug
Contact
Mailing List
Forums
Chat (IRC)
Twitter
Open Build Service (OBS)
is an
openSUSE project
.
浙ICP备2022010568号-2