Projects
openEuler:Mainline
python-zope-interface
Sign Up
Log In
Username
Password
We truncated the diff of some files because they were too big. If you want to see the full diff for every file,
click here
.
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,
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> - -Это ошибка спрашивать про интерфейсы реализуемые не вызываемым объектом:: -
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::
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` - это рассматривается как если бы
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' -
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)
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. - -
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
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)
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 = (
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
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''
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 +
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
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')
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 @@
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):
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