diff options
author | Michael Howitz <mh@gocept.com> | 2022-12-28 07:26:13 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-12-28 07:26:13 +0100 |
commit | f1a2a39fcc779a6dd10a161a2ced8c3cf488d9f2 (patch) | |
tree | b02d61b7bae5eb325614b1a0b9ef1160208606af | |
parent | f05a16b94f135a6262667aeb7591487e8eefafa7 (diff) | |
download | zope-interface-f1a2a39fcc779a6dd10a161a2ced8c3cf488d9f2.tar.gz |
Drop support for Python 2.7, 3.5, 3.6. (#266)
Co-authored-by: Jens Vagelpohl <jens@plyp.com>
48 files changed, 692 insertions, 1848 deletions
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 8741dd7..1c22654 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -96,11 +96,7 @@ jobs: fail-fast: false matrix: python-version: - - "2.7" - - "3.5" - - "pypy-2.7" - "pypy-3.7" - - "3.6" - "3.7" - "3.8" - "3.9" @@ -109,11 +105,7 @@ jobs: os: [ubuntu-20.04, macos-latest] exclude: - os: macos-latest - python-version: "pypy-2.7" - - os: macos-latest python-version: "pypy-3.7" - - os: macos-latest - python-version: "3.5" steps: - name: checkout @@ -141,15 +133,7 @@ jobs: restore-keys: | ${{ runner.os }}-pip- - - name: Install Build Dependencies (PyPy2) - if: > - startsWith(matrix.python-version, 'pypy-2.7') - run: | - pip install -U pip - pip install -U setuptools wheel twine "cffi != 1.15.1" - - name: Install Build Dependencies (other Python versions) - if: > - !startsWith(matrix.python-version, 'pypy-2.7') + - name: Install Build Dependencies run: | pip install -U pip pip install -U setuptools wheel twine cffi @@ -158,9 +142,6 @@ jobs: if: > startsWith(runner.os, 'Mac') && !(startsWith(matrix.python-version, 'pypy') - || matrix.python-version == '2.7' - || matrix.python-version == '3.5' - || matrix.python-version == '3.6' || matrix.python-version == '3.7') env: MACOSX_DEPLOYMENT_TARGET: 10.9 @@ -175,9 +156,6 @@ jobs: if: > startsWith(runner.os, 'Mac') && !(startsWith(matrix.python-version, 'pypy') - || matrix.python-version == '2.7' - || matrix.python-version == '3.5' - || matrix.python-version == '3.6' || matrix.python-version == '3.7') env: MACOSX_DEPLOYMENT_TARGET: 11.0 @@ -192,9 +170,6 @@ jobs: if: > !startsWith(runner.os, 'Mac') || startsWith(matrix.python-version, 'pypy') - || matrix.python-version == '2.7' - || matrix.python-version == '3.5' - || matrix.python-version == '3.6' || matrix.python-version == '3.7' run: | # Next, build the wheel *in place*. This helps ccache, and also lets us cache the configure @@ -205,7 +180,6 @@ jobs: - name: Install zope.interface and dependencies run: | # Install to collect dependencies into the (pip) cache. - pip install -U 'faulthandler; python_version == "2.7" and platform_python_implementation == "CPython"' pip install .[test] - name: Check zope.interface build @@ -223,9 +197,6 @@ jobs: if: > startsWith(runner.os, 'Mac') && !(startsWith(matrix.python-version, 'pypy') - || matrix.python-version == '2.7' - || matrix.python-version == '3.5' - || matrix.python-version == '3.6' || matrix.python-version == '3.7') uses: actions/upload-artifact@v3 with: @@ -262,11 +233,7 @@ jobs: fail-fast: false matrix: python-version: - - "2.7" - - "3.5" - - "pypy-2.7" - "pypy-3.7" - - "3.6" - "3.7" - "3.8" - "3.9" @@ -275,11 +242,7 @@ jobs: os: [ubuntu-20.04, macos-latest] exclude: - os: macos-latest - python-version: "pypy-2.7" - - os: macos-latest python-version: "pypy-3.7" - - os: macos-latest - python-version: "3.5" steps: - name: checkout @@ -320,7 +283,6 @@ jobs: run: | pip install -U wheel pip install -U --no-binary :all: coverage - pip install -U 'faulthandler; python_version == "2.7" and platform_python_implementation == "CPython"' # Unzip into src/ so that testrunner can find the .so files # when we ask it to load tests from that directory. This # might also save some build time? @@ -495,8 +457,6 @@ jobs: # An alternate way to do this is to run the container directly with a uses: # and then the script runs inside it. That may work better with caching. # See https://github.com/pyca/bcrypt/blob/f6b5ee2eda76d077c531362ac65e16f045cf1f29/.github/workflows/wheel-builder.yml - # The 2010 image is the most recent spec that comes with Python 2.7, - # and only up through the tag 2021-02-06-3d322a5 env: DOCKER_IMAGE: quay.io/pypa/${{ matrix.image }} run: | diff --git a/.manylinux-install.sh b/.manylinux-install.sh index 3eb634e..3da5a3b 100755 --- a/.manylinux-install.sh +++ b/.manylinux-install.sh @@ -28,9 +28,6 @@ yum -y install libffi-devel tox_env_map() { case $1 in - *"cp27"*) echo 'py27';; - *"cp35"*) echo 'py35';; - *"cp36"*) echo 'py36';; *"cp37"*) echo 'py37';; *"cp38"*) echo 'py38';; *"cp39"*) echo 'py39';; @@ -43,10 +40,7 @@ tox_env_map() { # Compile wheels for PYBIN in /opt/python/*/bin; do if \ - [[ "${PYBIN}" == *"cp27"* ]] || \ - [[ "${PYBIN}" == *"cp35"* ]] || \ [[ "${PYBIN}" == *"cp311"* ]] || \ - [[ "${PYBIN}" == *"cp36"* ]] || \ [[ "${PYBIN}" == *"cp37"* ]] || \ [[ "${PYBIN}" == *"cp38"* ]] || \ [[ "${PYBIN}" == *"cp39"* ]] || \ @@ -2,12 +2,11 @@ # https://github.com/zopefoundation/meta/tree/master/config/c-code [meta] template = "c-code" -commit-id = "342271a70d886e753e5cc629e8a81b3cfab692ac" +commit-id = "be727608" [python] with-appveyor = true with-pypy = true -with-legacy-python = true with-sphinx-doctests = true with-windows = false with-future-python = false @@ -26,7 +25,7 @@ testenv-setenv = [ ] coverage-command = "coverage combine" coverage-additional = [ - "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", ] @@ -63,7 +62,6 @@ additional-install = [ " run: |", " pip install -U wheel", " pip install -U --no-binary :all: coverage", - " pip install -U 'faulthandler; python_version == \"2.7\" and platform_python_implementation == \"CPython\"'", " # Unzip into src/ so that testrunner can find the .so files", " # when we ask it to load tests from that directory. This", " # might also save some build time?", diff --git a/CHANGES.rst b/CHANGES.rst index fdfea8c..47797e5 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -2,11 +2,18 @@ Changes ========= -5.5.3 (unreleased) -================== +6.0 (unreleased) +================ + +- Drop support for Python 2.7, 3.5, 3.6. - Fix test deprecation warning on Python 3.11. +- Drop: + + + `zope.interface.implements` + + `zope.interface.implementsOnly` + + `zope.interface.classProvides` 5.5.2 (2022-11-17) ================== diff --git a/appveyor.yml b/appveyor.yml index 6b5e352..ae189e5 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -10,9 +10,6 @@ environment: 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 diff --git a/docs/api/declarations.rst b/docs/api/declarations.rst index 57c11f0..f18b7b9 100644 --- a/docs/api/declarations.rst +++ b/docs/api/declarations.rst @@ -515,33 +515,6 @@ When registering an adapter or utility component, the registry looks for the 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 ================================== @@ -1,7 +1,7 @@ # Generated from: # https://github.com/zopefoundation/meta/tree/master/config/c-code [bdist_wheel] -universal = 1 +universal = 0 [zest.releaser] create-wheel = no @@ -100,7 +100,7 @@ long_description = ( ) setup(name='zope.interface', - version='5.5.3.dev0', + version='6.0.dev0', url='https://github.com/zopefoundation/zope.interface', license='ZPL 2.1', description='Interfaces for Python', @@ -113,11 +113,7 @@ setup(name='zope.interface', "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 @@ setup(name='zope.interface', 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, diff --git a/src/zope/interface/__init__.py b/src/zope/interface/__init__.py index 3372103..17a272f 100644 --- a/src/zope/interface/__init__.py +++ b/src/zope/interface/__init__.py @@ -62,14 +62,11 @@ from zope.interface.declarations import alsoProvides 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 diff --git a/src/zope/interface/_compat.py b/src/zope/interface/_compat.py index 3587463..2ff8d83 100644 --- a/src/zope/interface/_compat.py +++ b/src/zope/interface/_compat.py @@ -20,51 +20,16 @@ used during early bootstrapping. """ import os import sys -import types -if sys.version_info[0] < 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_info[0] >= 3, "Only on Python 2")(test_method) - - -def _skip_under_py2(test_method): - import unittest - return unittest.skipIf(sys.version_info[0] < 3, "Only on Python 3")(test_method) def _c_optimizations_required(): diff --git a/src/zope/interface/_zope_interface_coptimizations.c b/src/zope/interface/_zope_interface_coptimizations.c index af52a0a..9189928 100644 --- a/src/zope/interface/_zope_interface_coptimizations.c +++ b/src/zope/interface/_zope_interface_coptimizations.c @@ -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 @@ __adapt__(PyObject *self, PyObject *obj) return Py_None; } -#ifndef PY3K -typedef long Py_hash_t; -#endif - typedef struct { Spec spec; PyObject* __name__; @@ -1255,11 +1246,7 @@ _lookup(lookup *self, { 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 @@ _lookup1(lookup *self, { 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 @@ _adapter_hook(lookup *self, { 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"); diff --git a/src/zope/interface/adapter.py b/src/zope/interface/adapter.py index 9a542db..dbff0d1 100644 --- a/src/zope/interface/adapter.py +++ b/src/zope/interface/adapter.py @@ -23,7 +23,6 @@ from zope.interface import ro 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 @@ __all__ = [ # ``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 @@ class BaseAdapterRegistry(object): 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 @@ class BaseAdapterRegistry(object): 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 @@ class BaseAdapterRegistry(object): 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 @@ class BaseAdapterRegistry(object): .. 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 @@ class BaseAdapterRegistry(object): 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 @@ class BaseAdapterRegistry(object): self._subscribers, required, provided, - u'' + '' ) or () return subscriber if subscriber in subscribers else None @@ -486,7 +483,7 @@ class BaseAdapterRegistry(object): 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 @@ class BaseAdapterRegistry(object): return if new: - components[u''] = new + components[''] = new else: # Instead of setting components[u''] = new, we clean out # empty containers, since we don't want our keys to @@ -517,7 +514,7 @@ class BaseAdapterRegistry(object): # 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 components[u''] + del components[''] for comp, k in reversed(lookups): d = comp[k] if d: @@ -601,7 +598,7 @@ class BaseAdapterRegistry(object): _not_in_mapping = object() @_use_c_impl -class LookupBase(object): +class LookupBase: def __init__(self): self._cache = {} @@ -626,8 +623,8 @@ class LookupBase(object): 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 @@ class LookupBase(object): 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 @@ class LookupBase(object): 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 @@ class VerifyingBase(LookupBaseFallback): 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 @@ class AdapterLookupBase(object): r.subscribe(self) _refs[ref] = 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 @@ class AdapterLookupBase(object): 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 @@ class AdapterLookupBase(object): if extendors is None: continue - _subscriptions(byorder[order], required, extendors, u'', + _subscriptions(byorder[order], required, extendors, '', result, 0, order) self._subscribe(*required) @@ -922,7 +919,7 @@ class AdapterRegistry(BaseAdapterRegistry): # we need to keep track of our invalidating subregistries. self._v_subregistries = weakref.WeakKeyDictionary() - super(AdapterRegistry, self).__init__(bases) + super().__init__(bases) def _addSubregistry(self, r): self._v_subregistries[r] = 1 @@ -940,10 +937,10 @@ class AdapterRegistry(BaseAdapterRegistry): if r not in old: r._addSubregistry(self) - super(AdapterRegistry, self)._setBases(bases) + super()._setBases(bases) def changed(self, originally_changed): - super(AdapterRegistry, self).changed(originally_changed) + super().changed(originally_changed) for sub in self._v_subregistries.keys(): sub.changed(originally_changed) diff --git a/src/zope/interface/advice.py b/src/zope/interface/advice.py index 86d0f11..54e356e 100644 --- a/src/zope/interface/advice.py +++ b/src/zope/interface/advice.py @@ -26,15 +26,8 @@ Visit the PEAK home page at http://peak.telecommunity.com for more information. """ 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 @@ def getFrameInfo(frame): 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 @@ def determineMetaclass(bases, explicit_mc=None): 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 candidates[0] @@ -195,9 +103,6 @@ def determineMetaclass(bases, explicit_mc=None): 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: diff --git a/src/zope/interface/common/__init__.py b/src/zope/interface/common/__init__.py index 137e938..56f4566 100644 --- a/src/zope/interface/common/__init__.py +++ b/src/zope/interface/common/__init__.py @@ -28,7 +28,7 @@ __all__ = [ # 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 @@ class ABCInterfaceClass(InterfaceClass): 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 @@ class ABCInterfaceClass(InterfaceClass): 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 @@ class ABCInterfaceClass(InterfaceClass): based_on_doc = based_on_doc.splitlines() based_on_doc = based_on_doc[0] 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), diff --git a/src/zope/interface/common/builtins.py b/src/zope/interface/common/builtins.py index a07c0a3..17090e4 100644 --- a/src/zope/interface/common/builtins.py +++ b/src/zope/interface/common/builtins.py @@ -17,7 +17,6 @@ that they implement the appropriate interface. .. versionadded:: 5.0.0 """ -from __future__ import absolute_import from zope.interface import classImplements @@ -60,12 +59,11 @@ class ITuple(collections.ISequence): 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 @@ class IByteString(collections.IByteString): 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 @@ class IFile(io.IIOBase): many different classes that implement different interfaces from :mod:`zope.interface.common.io`. """ - try: - extra_classes = (file,) - except NameError: - extra_classes = () + extra_classes = () diff --git a/src/zope/interface/common/collections.py b/src/zope/interface/common/collections.py index 00e2b8c..c549028 100644 --- a/src/zope/interface/common/collections.py +++ b/src/zope/interface/common/collections.py @@ -29,37 +29,16 @@ is, ``verifyObject(ISequence, list()))`` will pass, for example), a few might no .. 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 @@ from zope.interface.common import optional # 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 @@ class IIterator(IIterable): 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 IReversible(IIterable): """ 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 ISized(ABCInterface): 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 @@ class IByteString(ISequence): """ 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 @@ class IMapping(ICollection): # 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 IValuesView(IMappingView, ICollection): """ 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) diff --git a/src/zope/interface/common/interfaces.py b/src/zope/interface/common/interfaces.py index 4308e0a..70bd294 100644 --- a/src/zope/interface/common/interfaces.py +++ b/src/zope/interface/common/interfaces.py @@ -22,11 +22,7 @@ classImplements(Exception, IException) 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): diff --git a/src/zope/interface/common/io.py b/src/zope/interface/common/io.py index 540d53a..0d6f3ba 100644 --- a/src/zope/interface/common/io.py +++ b/src/zope/interface/common/io.py @@ -18,7 +18,6 @@ that they implement the appropriate interface. .. versionadded:: 5.0.0 """ -from __future__ import absolute_import import io as abc @@ -37,16 +36,7 @@ class IRawIOBase(IIOBase): 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): diff --git a/src/zope/interface/common/mapping.py b/src/zope/interface/common/mapping.py index de56cf8..d043333 100644 --- a/src/zope/interface/common/mapping.py +++ b/src/zope/interface/common/mapping.py @@ -29,7 +29,6 @@ implement ``IMutableMapping``, but *do not* implement any of the 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 @@ class IIterableMapping(IEnumerableMapping): """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 @@ class IExtendedReadMapping(IIterableMapping): """ 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. diff --git a/src/zope/interface/common/numbers.py b/src/zope/interface/common/numbers.py index 3bf9206..6b20e09 100644 --- a/src/zope/interface/common/numbers.py +++ b/src/zope/interface/common/numbers.py @@ -18,14 +18,12 @@ that they implement the appropriate interface. .. 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 @@ class IComplex(INumber): 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 @@ class IReal(IComplex): __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 diff --git a/src/zope/interface/common/sequence.py b/src/zope/interface/common/sequence.py index da4bc84..5edc73d 100644 --- a/src/zope/interface/common/sequence.py +++ b/src/zope/interface/common/sequence.py @@ -32,7 +32,6 @@ in this module. __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 @@ class IReadSequence(collections.IContainer, IFiniteSequence): def __rmul__(n): """``x.__rmul__(n) <==> n * x``""" - if PY2: - def __getslice__(i, j): - """``x.__getslice__(i, j) <==> x[i: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 @@ class IUniqueMemberWriteSequence(Interface): supports slice objects. """ - if PY2: - def __setslice__(i, j, other): - """``x.__setslice__(i, j, other) <==> x[i: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 x[i: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``""" diff --git a/src/zope/interface/common/tests/__init__.py b/src/zope/interface/common/tests/__init__.py index 2023072..0503495 100644 --- a/src/zope/interface/common/tests/__init__.py +++ b/src/zope/interface/common/tests/__init__.py @@ -60,7 +60,7 @@ def add_verify_tests(cls, iface_classes_iter): self.assertTrue(self.verify(iface, stdlib_class)) - suffix = "%s_%s_%s_%s" % ( + suffix = "{}_{}_{}_{}".format( stdlib_class.__module__.replace('.', '_'), stdlib_class.__name__, iface.__module__.replace('.', '_'), diff --git a/src/zope/interface/common/tests/basemapping.py b/src/zope/interface/common/tests/basemapping.py index b756dca..6fe91a1 100644 --- a/src/zope/interface/common/tests/basemapping.py +++ b/src/zope/interface/common/tests/basemapping.py @@ -63,7 +63,7 @@ def testIEnumerableMapping(self, inst, state): test___len__(self, inst, state) -class BaseTestIReadMapping(object): +class BaseTestIReadMapping: def testIReadMapping(self): inst = self._IReadMapping__sample() state = self._IReadMapping__stateDict() diff --git a/src/zope/interface/common/tests/test_builtins.py b/src/zope/interface/common/tests/test_builtins.py index 1f0d338..cf7019b 100644 --- a/src/zope/interface/common/tests/test_builtins.py +++ b/src/zope/interface/common/tests/test_builtins.py @@ -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 @@ class TestVerifyClass(VerifyClassMixin, 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, ()), )) diff --git a/src/zope/interface/common/tests/test_collections.py b/src/zope/interface/common/tests/test_collections.py index 152626b..2bd6f50 100644 --- a/src/zope/interface/common/tests/test_collections.py +++ b/src/zope/interface/common/tests/test_collections.py @@ -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.common import collections 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 @@ class TestVerifyClass(VerifyClassMixin, unittest.TestCase): 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 @@ class TestVerifyClass(VerifyClassMixin, unittest.TestCase): # 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 @@ class TestVerifyObject(VerifyObjectMixin, 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 @@ class TestVerifyObject(VerifyObjectMixin, 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, + } diff --git a/src/zope/interface/common/tests/test_io.py b/src/zope/interface/common/tests/test_io.py index c6ff8bd..0e8e74d 100644 --- a/src/zope/interface/common/tests/test_io.py +++ b/src/zope/interface/common/tests/test_io.py @@ -40,13 +40,3 @@ class TestVerifyObject(VerifyObjectMixin, 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, - }) diff --git a/src/zope/interface/declarations.py b/src/zope/interface/declarations.py index 59bd650..b3e3f21 100644 --- a/src/zope/interface/declarations.py +++ b/src/zope/interface/declarations.py @@ -32,14 +32,11 @@ from types import MethodType 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 @@ __all__ = [ # 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 @@ def _next_super_class(ob): next_class = complete_mro[complete_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 @@ class _ImmutableDeclaration(Declaration): @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 @@ class Implements(NameAndModuleComparisonMixin, 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 @@ class Implements(NameAndModuleComparisonMixin, 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 @@ def implementedBy(cls): # pylint:disable=too-many-return-statements,too-many-bra 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 @@ def _implements_advice(cls): return cls -class implementer(object): +class implementer: """ Declare the interfaces implemented by instances of a class. @@ -670,9 +661,8 @@ class implementer(object): 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 @@ class implementer(object): 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 @@ class implementer_only(object): 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 @@ class Provides(Declaration): # Really named ProvidesClass if len(mod_names) == 1: mod_names = "sys.modules[%r]" % mod_names[0] ordered_names = ( - '%s, ' % (mod_names,) + '{}, '.format(mod_names) ) + ordered_names - return "%s(%s)" % ( + return "{}({})".format( function_name, ordered_names, ) @@ -908,10 +816,9 @@ def directlyProvides(object, *interfaces): # pylint:disable=redefined-builtin cls = getattr(object, '__class__', None) if cls is not None and getattr(cls, '__class__', None) is cls: # It's a meta class (well, at least it it could be an extension class) - # Note that we can't get here from Py3k tests: there is no normal + # Note that we can't get here from the tests: there is no normal # class which isn't descriptor aware. - if not isinstance(object, - DescriptorAwareMetaClasses): + if not isinstance(object, type): raise TypeError("Attempt to make an interface declaration on a " "non-descriptor-aware class") @@ -919,12 +826,7 @@ def directlyProvides(object, *interfaces): # pylint:disable=redefined-builtin if cls is None: cls = type(object) - issub = False - for damc in DescriptorAwareMetaClasses: - if issubclass(cls, damc): - issub = True - break - if issub: + if issubclass(cls, type): # we have a class or type. We'll use a special descriptor # that provides some extra caching object.__provides__ = ClassProvides(object, cls, *interfaces) @@ -1011,7 +913,7 @@ class ClassProvides(Declaration, ClassProvidesBase): # Thus, as our repr, we go with the ``directlyProvides()`` syntax. interfaces = (self._cls, ) + self.__args[2:] ordered_names = self._argument_names_for_repr(interfaces) - return "directlyProvides(%s)" % (ordered_names,) + return "directlyProvides({})".format(ordered_names) def __reduce__(self): return self.__class__, self.__args @@ -1039,7 +941,7 @@ def directlyProvidedBy(object): # pylint:disable=redefined-builtin return Declaration(provides.__bases__[:-1]) -def classProvides(*interfaces): +class provider: """Declare interfaces provided directly by a class This function is called in a class definition. @@ -1059,47 +961,16 @@ def classProvides(*interfaces): This function is provided for convenience. It provides a more convenient way to call `directlyProvides` for a class. For example:: - classProvides(I1) + @provider(I1) + class C: + pass is equivalent to calling:: - directlyProvides(theclass, I1) + directlyProvides(C, I1) after the class has been created. """ - # This entire approach is invalid under Py3K. Don't even try to fix - # the coverage for this block there. :( - - if PYTHON3: - raise TypeError(_ADVICE_ERROR % 'provider') - - frame = sys._getframe(1) # pylint:disable=protected-access - locals = frame.f_locals # pylint:disable=redefined-builtin - - # Try to make sure we were called from a class def - if (locals is frame.f_globals) or ('__module__' not in locals): - raise TypeError("classProvides can be used only from a " - "class definition.") - - if '__provides__' in locals: - raise TypeError( - "classProvides can only be used once in a class definition.") - - locals["__provides__"] = _normalizeargs(interfaces) - - addClassAdvisor(_classProvides_advice, depth=2) - -def _classProvides_advice(cls): - # This entire approach is invalid under Py3K. Don't even try to fix - # the coverage for this block there. :( - interfaces = cls.__dict__['__provides__'] - del cls.__provides__ - directlyProvides(cls, *interfaces) - return cls - - -class provider(object): - """Class decorator version of classProvides""" def __init__(self, *interfaces): self.interfaces = interfaces @@ -1257,7 +1128,7 @@ def providedBy(ob): @_use_c_impl -class ObjectSpecificationDescriptor(object): +class ObjectSpecificationDescriptor: """Implement the ``__providedBy__`` attribute The ``__providedBy__`` attribute computes the interfaces provided by diff --git a/src/zope/interface/document.py b/src/zope/interface/document.py index 309bb57..84cfaa0 100644 --- a/src/zope/interface/document.py +++ b/src/zope/interface/document.py @@ -32,7 +32,7 @@ def asStructuredText(I, munge=0, rst=False): """ if rst: - inline_literal = lambda s: "``%s``" % (s,) + inline_literal = lambda s: "``{}``".format(s) else: inline_literal = lambda s: s @@ -61,7 +61,7 @@ def asStructuredText(I, munge=0, rst=False): 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 @@ def asStructuredText(I, munge=0, rst=False): 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)) diff --git a/src/zope/interface/exceptions.py b/src/zope/interface/exceptions.py index 47c351b..d5c234a 100644 --- a/src/zope/interface/exceptions.py +++ b/src/zope/interface/exceptions.py @@ -92,7 +92,7 @@ class _TargetInvalid(Invalid): 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 @@ class _TargetInvalid(Invalid): _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 @@ class BrokenMethodImplementation(_TargetInvalid): 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 @@ class MultipleInvalid(_TargetInvalid): _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): diff --git a/src/zope/interface/interface.py b/src/zope/interface/interface.py index 7447641..1bd6f9e 100644 --- a/src/zope/interface/interface.py +++ b/src/zope/interface/interface.py @@ -20,7 +20,6 @@ from types import FunctionType 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 @@ def taggedValue(key, value): return _decorator_non_return -class Element(object): +class Element: """ Default implementation of `zope.interface.interfaces.IElement`. """ @@ -128,7 +127,7 @@ SpecificationBasePy = object # filled by _use_c_impl. @_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 @@ class SpecificationBase(object): __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 @@ class _InterfaceMetaClass(type): return cls.__module def __repr__(cls): - return "<class '%s.%s'>" % ( + return "<class '{}.{}'>".format( cls.__module, cls.__name__, ) @@ -720,27 +719,6 @@ class InterfaceClass(_InterfaceClassBase): 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 @@ class InterfaceClass(_InterfaceClassBase): 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 @@ class InterfaceClass(_InterfaceClassBase): 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 @@ class InterfaceClass(_InterfaceClassBase): 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 @@ class Attribute(Element): 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), diff --git a/src/zope/interface/interfaces.py b/src/zope/interface/interfaces.py index 66aecb9..2b67ce1 100644 --- a/src/zope/interface/interfaces.py +++ b/src/zope/interface/interfaces.py @@ -754,122 +754,9 @@ class IInterfaceDeclaration(Interface): .. 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 @@ class IAdapterRegistry(Interface): 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 @@ class IAdapterRegistry(Interface): 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 @@ class IAdapterRegistry(Interface): 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 @@ class IObjectEvent(Interface): @implementer(IObjectEvent) -class ObjectEvent(object): +class ObjectEvent: def __init__(self, object): # pylint:disable=redefined-builtin self.object = object @@ -1102,26 +989,26 @@ class IComponentLookup(Interface): utilities = Attribute( "Adapter Registry to manage all registered utilities.") - def queryAdapter(object, interface, name=u'', default=None): # pylint:disable=redefined-builtin + def queryAdapter(object, interface, name='', default=None): # pylint:disable=redefined-builtin """Look for a named adapter to an interface for an object If a matching adapter cannot be found, returns the default. """ - def getAdapter(object, interface, name=u''): # pylint:disable=redefined-builtin + def getAdapter(object, interface, name=''): # pylint:disable=redefined-builtin """Look for a named adapter to an interface for an object If a matching adapter cannot be found, a `ComponentLookupError` is raised. """ - def queryMultiAdapter(objects, interface, name=u'', default=None): + def queryMultiAdapter(objects, interface, name='', default=None): """Look for a multi-adapter to an interface for multiple objects If a matching adapter cannot be found, returns the default. """ - def getMultiAdapter(objects, interface, name=u''): + def getMultiAdapter(objects, interface, name=''): """Look for a multi-adapter to an interface for multiple objects If a matching adapter cannot be found, a `ComponentLookupError` @@ -1239,7 +1126,7 @@ class RegistrationEvent(ObjectEvent): """There has been a change in a registration """ def __repr__(self): - return "%s event:\n%r" % (self.__class__.__name__, self.object) + return "{} event:\n{!r}".format(self.__class__.__name__, self.object) class IRegistered(IRegistrationEvent): """A component or factory was registered @@ -1263,8 +1150,8 @@ class IComponentRegistry(Interface): """Register components """ - def registerUtility(component=None, provided=None, name=u'', - info=u'', factory=None): + def registerUtility(component=None, provided=None, name='', + info='', factory=None): """Register a utility :param factory: @@ -1291,7 +1178,7 @@ class IComponentRegistry(Interface): A `IRegistered` event is generated with an `IUtilityRegistration`. """ - def unregisterUtility(component=None, provided=None, name=u'', + def unregisterUtility(component=None, provided=None, name='', factory=None): """Unregister a utility @@ -1331,8 +1218,8 @@ class IComponentRegistry(Interface): in the object. """ - def registerAdapter(factory, required=None, provided=None, name=u'', - info=u''): + def registerAdapter(factory, required=None, provided=None, name='', + info=''): """Register an adapter factory :param factory: @@ -1367,7 +1254,7 @@ class IComponentRegistry(Interface): """ def unregisterAdapter(factory=None, required=None, - provided=None, name=u''): + provided=None, name=''): """Unregister an adapter factory :returns: @@ -1416,7 +1303,7 @@ class IComponentRegistry(Interface): """ def registerSubscriptionAdapter(factory, required=None, provides=None, - name=u'', info=''): + name='', info=''): """Register a subscriber factory :param factory: @@ -1454,7 +1341,7 @@ class IComponentRegistry(Interface): """ def unregisterSubscriptionAdapter(factory=None, required=None, - provides=None, name=u''): + provides=None, name=''): """Unregister a subscriber factory. :returns: @@ -1506,7 +1393,7 @@ class IComponentRegistry(Interface): registrations in the object. """ - def registerHandler(handler, required=None, name=u'', info=''): + def registerHandler(handler, required=None, name='', info=''): """Register a handler. A handler is a subscriber that doesn't compute an adapter @@ -1541,7 +1428,7 @@ class IComponentRegistry(Interface): A `IRegistered` event is generated with an `IHandlerRegistration`. """ - def unregisterHandler(handler=None, required=None, name=u''): + def unregisterHandler(handler=None, required=None, name=''): """Unregister a handler. A handler is a subscriber that doesn't compute an adapter diff --git a/src/zope/interface/registry.py b/src/zope/interface/registry.py index 4fdb120..292499d 100644 --- a/src/zope/interface/registry.py +++ b/src/zope/interface/registry.py @@ -36,8 +36,6 @@ from zope.interface.declarations import implementer 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 @@ __all__ = [ 'Components', ] -class _UnhashableComponentCounter(object): +class _UnhashableComponentCounter: # defaultdict(int)-like object for unhashable components def __init__(self, otherdict): @@ -76,7 +74,7 @@ class _UnhashableComponentCounter(object): def _defaultdict_int(): return defaultdict(int) -class _UtilityRegistrations(object): +class _UtilityRegistrations: def __init__(self, utilities, utility_registrations): # {provided -> {component: count}} @@ -144,14 +142,14 @@ class _UtilityRegistrations(object): @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 @@ class Components(object): 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 @@ class Components(object): 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 @@ class Components(object): 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 @@ class Components(object): 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 @@ class Components(object): ) 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 @@ class Components(object): 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 @@ class Components(object): 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 @@ class Components(object): 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 @@ class Components(object): 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 @@ class Components(object): 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 @@ class Components(object): 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 @@ def _getName(component): try: return component.__component_name__ except AttributeError: - return u'' + return '' def _getUtilityProvided(component): provided = list(providedBy(component)) @@ -612,7 +609,7 @@ def _getAdapterRequired(factory, required): if r is None: r = Interface elif not ISpecification.providedBy(r): - if isinstance(r, CLASS_TYPES): + if isinstance(r, type): r = implementedBy(r) else: raise TypeError("Required specification must be a " @@ -623,7 +620,7 @@ def _getAdapterRequired(factory, required): @implementer(IUtilityRegistration) -class UtilityRegistration(object): +class UtilityRegistration: def __init__(self, registry, provided, name, component, doc, factory=None): (self.registry, self.provided, self.name, self.component, self.info, @@ -631,7 +628,7 @@ class UtilityRegistration(object): ) = registry, provided, name, component, doc, factory def __repr__(self): - return '%s(%r, %s, %r, %s, %r, %r)' % ( + return '{}({!r}, {}, {!r}, {}, {!r}, {!r})'.format( self.__class__.__name__, self.registry, getattr(self.provided, '__name__', None), self.name, @@ -661,7 +658,7 @@ class UtilityRegistration(object): return repr(self) >= repr(other) @implementer(IAdapterRegistration) -class AdapterRegistration(object): +class AdapterRegistration: def __init__(self, registry, required, provided, name, component, doc): (self.registry, self.required, self.provided, self.name, @@ -669,7 +666,7 @@ class AdapterRegistration(object): ) = registry, required, provided, name, component, doc def __repr__(self): - return '%s(%r, %s, %s, %r, %s, %r)' % ( + return '{}({!r}, {}, {}, {!r}, {}, {!r})'.format( self.__class__.__name__, self.registry, '[' + ", ".join([r.__name__ for r in self.required]) + ']', @@ -717,7 +714,7 @@ class HandlerRegistration(AdapterRegistration): provided = None def __repr__(self): - return '%s(%r, %s, %r, %s, %r)' % ( + return '{}({!r}, {}, {!r}, {}, {!r})'.format( self.__class__.__name__, self.registry, '[' + ", ".join([r.__name__ for r in self.required]) + ']', diff --git a/src/zope/interface/ro.py b/src/zope/interface/ro.py index 89dde67..17468e9 100644 --- a/src/zope/interface/ro.py +++ b/src/zope/interface/ro.py @@ -80,7 +80,6 @@ this, *also* enable ``ZOPE_INTERFACE_LOG_CHANGED_IRO`` and examine the 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 @@ class InconsistentResolutionOrderError(TypeError): 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 @@ class _NamedBool(int): # cannot actually inherit bool 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 @@ class _ClassBoolFromEnv(object): 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 @@ class _StaticMRO(object): return list(self.__mro) -class C3(object): +class C3: # Holds the shared state during computation of an MRO. @staticmethod @@ -465,19 +464,19 @@ class _TrackingC3(C3): 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 @@ class _ROComparison(object): 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 @@ class _ROComparison(object): 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 @@ class _ROComparison(object): 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, ) diff --git a/src/zope/interface/tests/__init__.py b/src/zope/interface/tests/__init__.py index 6a11218..04ff939 100644 --- a/src/zope/interface/tests/__init__.py +++ b/src/zope/interface/tests/__init__.py @@ -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 @@ class OptimizationTestMixin(object): 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 @@ class MissingSomeAttrs(object): try: from zope.testing import cleanup except ImportError: - class CleanUp(object): + class CleanUp: def cleanUp(self): pass diff --git a/src/zope/interface/tests/advisory_testing.py b/src/zope/interface/tests/advisory_testing.py index b159e93..bed9dd8 100644 --- a/src/zope/interface/tests/advisory_testing.py +++ b/src/zope/interface/tests/advisory_testing.py @@ -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 diff --git a/src/zope/interface/tests/odd.py b/src/zope/interface/tests/odd.py index 74c6158..27b42ca 100644 --- a/src/zope/interface/tests/odd.py +++ b/src/zope/interface/tests/odd.py @@ -55,10 +55,6 @@ This is used for testing support for ExtensionClass in new interfaces. >>> C.c = 1 >>> c.c 1 - >>> import sys - >>> if sys.version[0] == '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 @@ class MetaMetaClass(type): return type.__getattribute__(cls, name) -class MetaClass(object): +class MetaClass: """Odd classes """ @@ -95,7 +91,7 @@ class MetaClass(object): 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 @@ MetaClass = MetaMetaClass('MetaClass', {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 @@ class OddInstance(object): 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))) diff --git a/src/zope/interface/tests/test_adapter.py b/src/zope/interface/tests/test_adapter.py index 2ab84ca..203ba81 100644 --- a/src/zope/interface/tests/test_adapter.py +++ b/src/zope/interface/tests/test_adapter.py @@ -50,7 +50,7 @@ def _makeInterfaces(): # 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._data[name] @@ -112,7 +112,7 @@ class BaseAdapterRegistryTests(unittest.TestCase): 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 @@ class BaseAdapterRegistryTests(unittest.TestCase): 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 @@ class LookupBaseFallbackTests(unittest.TestCase): 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 @@ class VerifyingBaseFallbackTests(unittest.TestCase): _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 @@ class AdapterLookupBaseTests(unittest.TestCase): 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 @@ class AdapterLookupBaseTests(unittest.TestCase): 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 @@ class AdapterLookupBaseTests(unittest.TestCase): IFoo = InterfaceClass('IFoo') IBar = InterfaceClass('IBar', (IFoo,)) @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() registry = self._makeRegistry() @@ -1653,9 +1653,7 @@ class AdapterLookupBaseTests(unittest.TestCase): 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 @@ class AdapterLookupBaseTests(unittest.TestCase): 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 @@ class AdapterLookupBaseTests(unittest.TestCase): 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 @@ class AdapterLookupBaseTests(unittest.TestCase): alb.lookup = lookup objects = [ - super(AdapterLookupBaseTests, self), + super(), 42, "abc", - super(AdapterLookupBaseTests, self), + super(), ] result = alb.queryMultiAdapter(objects, None) @@ -1906,7 +1904,7 @@ class AdapterLookupBaseTests(unittest.TestCase): 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 @@ class AdapterLookupBaseTests(unittest.TestCase): 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 @@ class AdapterLookupBaseTests(unittest.TestCase): 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 @@ class AdapterRegistryTests(VerifyingAdapterRegistryTests): 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 @@ class Test_utils(unittest.TestCase): 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 @@ class Test_utils(unittest.TestCase): 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): diff --git a/src/zope/interface/tests/test_advice.py b/src/zope/interface/tests/test_advice.py index 0739ac1..caf5ee7 100644 --- a/src/zope/interface/tests/test_advice.py +++ b/src/zope/interface/tests/test_advice.py @@ -28,9 +28,6 @@ Visit the PEAK home page at http://peak.telecommunity.com for more information. 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 @@ class FrameInfoTest(unittest.TestCase): 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 @@ import sys 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 @@ class Test_determineMetaclass(unittest.TestCase): 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 @@ class Test_determineMetaclass(unittest.TestCase): pass self.assertEqual(self._callFUT((Meta,)), type) - @_skip_under_py3k def test_meta_of_class(self): class Metameta(type): pass - - class Meta(type): - __metaclass__ = Metameta - - self.assertEqual(self._callFUT((Meta, type)), Metameta) - - @_skip_under_py2 - def test_meta_of_class_py3k(self): - # Work around SyntaxError under Python2. - EXEC = '\n'.join([ - 'class Metameta(type):', - ' pass', - 'class Meta(type, metaclass=Metameta):', - ' pass', - ]) - globs = {} - exec(EXEC, globs) - Meta = globs['Meta'] - Metameta = globs['Metameta'] + class Meta(type, metaclass=Metameta): + pass self.assertEqual(self._callFUT((Meta, type)), Metameta) - @_skip_under_py3k - def test_multiple_in_hierarchy(self): + def test_multiple_in_hierarchy_py3k(self): class Meta_A(type): pass + class Meta_B(Meta_A): pass - class A(type): - __metaclass__ = Meta_A - class B(type): - __metaclass__ = Meta_B - self.assertEqual(self._callFUT((A, B,)), Meta_B) - @_skip_under_py2 - def test_multiple_in_hierarchy_py3k(self): - # Work around SyntaxError under Python2. - EXEC = '\n'.join([ - 'class Meta_A(type):', - ' pass', - 'class Meta_B(Meta_A):', - ' pass', - 'class A(type, metaclass=Meta_A):', - ' pass', - 'class B(type, metaclass=Meta_B):', - ' pass', - ]) - globs = {} - exec(EXEC, globs) - Meta_A = globs['Meta_A'] - Meta_B = globs['Meta_B'] - A = globs['A'] - B = globs['B'] + class A(type, metaclass=Meta_A): + pass + + class B(type, metaclass=Meta_B): + pass + self.assertEqual(self._callFUT((A, B)), Meta_B) - @_skip_under_py3k - def test_multiple_not_in_hierarchy(self): + + def test_multiple_not_in_hierarchy_py3k(self): class Meta_A(type): pass + class Meta_B(type): pass - class A(type): - __metaclass__ = Meta_A - class B(type): - __metaclass__ = Meta_B - self.assertRaises(TypeError, self._callFUT, (A, B,)) - @_skip_under_py2 - def test_multiple_not_in_hierarchy_py3k(self): - # Work around SyntaxError under Python2. - EXEC = '\n'.join([ - 'class Meta_A(type):', - ' pass', - 'class Meta_B(type):', - ' pass', - 'class A(type, metaclass=Meta_A):', - ' pass', - 'class B(type, metaclass=Meta_B):', - ' pass', - ]) - globs = {} - exec(EXEC, globs) - Meta_A = globs['Meta_A'] - Meta_B = globs['Meta_B'] - A = globs['A'] - B = globs['B'] + class A(type, metaclass=Meta_A): + pass + + class B(type, metaclass=Meta_B): + pass + self.assertRaises(TypeError, self._callFUT, (A, B)) @@ -312,34 +160,22 @@ class Test_minimalBases(unittest.TestCase): def test_empty(self): self.assertEqual(self._callFUT([]), []) - @_skip_under_py3k - def test_w_oldstyle_meta(self): - class C: - pass - self.assertEqual(self._callFUT([type(C)]), []) - - @_skip_under_py3k - def test_w_oldstyle_class(self): - class C: - pass - self.assertEqual(self._callFUT([C]), [C]) - def test_w_newstyle_meta(self): self.assertEqual(self._callFUT([type]), [type]) def test_w_newstyle_class(self): - class C(object): + class C: pass self.assertEqual(self._callFUT([C]), [C]) def test_simple_hierarchy_skips_implied(self): - class A(object): + class A: pass class B(A): pass class C(B): pass - class D(object): + class D: pass self.assertEqual(self._callFUT([A, B, C]), [C]) self.assertEqual(self._callFUT([A, C]), [C]) @@ -348,8 +184,8 @@ class Test_minimalBases(unittest.TestCase): self.assertEqual(self._callFUT([D, B, D]), [B, D]) def test_repeats_kicked_to_end_of_queue(self): - class A(object): + class A: pass - class B(object): + class B: pass self.assertEqual(self._callFUT([A, B, A]), [B, A]) diff --git a/src/zope/interface/tests/test_declarations.py b/src/zope/interface/tests/test_declarations.py index a01d39f..c17e323 100644 --- a/src/zope/interface/tests/test_declarations.py +++ b/src/zope/interface/tests/test_declarations.py @@ -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 @@ from zope.interface.tests.test_interface import NameAndModuleComparisonTestsMixi # 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 @@ class _Py3ClassAdvice(object): 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 @@ class NamedTests(unittest.TestCase): 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 @@ class DeclarationTests(EmptyDeclarationTests): pass @implementer(IBase) - class Base(object): + class Base: pass with C3Setting(ro.C3.STRICT_IRO, True): @@ -419,7 +413,7 @@ class TestImplements(NameAndModuleComparisonTestsMixin, def _makeOneToCompare(self): from zope.interface.declarations import implementedBy - class A(object): + class A: pass return implementedBy(A) @@ -443,9 +437,9 @@ class TestImplements(NameAndModuleComparisonTestsMixin, 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 @@ class TestImplements(NameAndModuleComparisonTestsMixin, 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 @@ class TestImplements(NameAndModuleComparisonTestsMixin, 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 @@ class Test_implementedByFallback(unittest.TestCase): 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 @@ class Test_implementedByFallback(unittest.TestCase): 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 @@ class Test_implementedByFallback(unittest.TestCase): 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 @@ class Test_implementedByFallback(unittest.TestCase): 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 @@ class Test_implementedByFallback(unittest.TestCase): 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 @@ class Test_implementedByFallback(unittest.TestCase): 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 @@ class Test_implementedByFallback(unittest.TestCase): def test_w_None_no_bases_w_class(self): from zope.interface.declarations import ClassProvides - class Foo(object): + class Foo: __implemented__ = None spec = self._callFUT(Foo) self.assertEqual(spec.__name__, @@ -669,7 +663,7 @@ class Test_implementedByFallback(unittest.TestCase): def test_w_existing_Implements(self): from zope.interface.declarations import Implements impl = Implements() - class Foo(object): + class Foo: __implemented__ = impl self.assertTrue(self._callFUT(Foo) is impl) @@ -684,7 +678,7 @@ class Test_implementedByFallback(unittest.TestCase): pass @implementer(IBase) - class Base(object): + class Base: pass @implementer(IDerived) @@ -706,7 +700,7 @@ class Test_implementedByFallback(unittest.TestCase): pass @implementer(IBase) - class Base(object): + class Base: pass class Child1(Base): @@ -734,7 +728,7 @@ class Test_implementedByFallback(unittest.TestCase): pass - class Base(object): + class Base: pass class Child1(Base): @@ -765,7 +759,7 @@ class Test_implementedByFallback(unittest.TestCase): class IDerived(IBase): pass - class Base(object): + class Base: pass @implementer(IDerived) @@ -788,7 +782,7 @@ class Test_implementedByFallback(unittest.TestCase): pass @implementer(IDerived) - class Derived(object): + class Derived: pass self.assertEqual(list(self._callFUT(Derived)), [IDerived]) @@ -815,7 +809,7 @@ class Test_implementedByFallback(unittest.TestCase): pass @implementer(IBase) - class Base(object): + class Base: pass @implementer(IM1) @@ -854,7 +848,7 @@ class Test_implementedBy(Test_implementedByFallback, return implementedBy -class _ImplementsTestMixin(object): +class _ImplementsTestMixin: FUT_SETS_PROVIDED_BY = True def _callFUT(self, cls, iface): @@ -888,17 +882,11 @@ class _ImplementsTestMixin(object): return Foo, IFoo - def test_oldstyle_class(self): - # This only matters on Python 2 + def test_class(self): class Foo: pass self._check_implementer(Foo) - def test_newstyle_class(self): - class Foo(object): - pass - self._check_implementer(Foo) - class Test_classImplementsOnly(_ImplementsTestMixin, unittest.TestCase): FUT_SETS_PROVIDED_BY = False @@ -914,7 +902,7 @@ class Test_classImplementsOnly(_ImplementsTestMixin, unittest.TestCase): IBar = InterfaceClass('IBar') impl = Implements(IFoo) impl.declared = (IFoo,) - class Foo(object): + class Foo: __implemented__ = impl impl.inherit = Foo self._callFUT(Foo, IBar) @@ -923,7 +911,7 @@ class Test_classImplementsOnly(_ImplementsTestMixin, unittest.TestCase): self.assertEqual(impl.inherit, None) self.assertEqual(impl.declared, (IBar,)) - def test_oldstyle_class(self): + def test_class(self): from zope.interface.declarations import Implements from zope.interface.interface import InterfaceClass IBar = InterfaceClass('IBar') @@ -933,16 +921,6 @@ class Test_classImplementsOnly(_ImplementsTestMixin, unittest.TestCase): __implemented__ = old_spec self._check_implementer(Foo, old_spec, '?', inherit=None) - def test_newstyle_class(self): - from zope.interface.declarations import Implements - from zope.interface.interface import InterfaceClass - IBar = InterfaceClass('IBar') - old_spec = Implements(IBar) - - class Foo(object): - __implemented__ = old_spec - self._check_implementer(Foo, old_spec, '?', inherit=None) - def test_redundant_with_super_still_implements(self): Base, IBase = self._check_implementer( @@ -984,11 +962,7 @@ class Test_classImplements(_ImplementsTestMixin, unittest.TestCase): self.assertTrue(IBase.providedBy(Child())) - def test_redundant_implementer_empty_class_declarations_newstyle(self): - self.__check_implementer_redundant(type('Foo', (object,), {})) - - def test_redundant_implementer_empty_class_declarations_oldstyle(self): - # This only matters on Python 2 + def test_redundant_implementer_empty_class_declarations(self): class Foo: pass self.__check_implementer_redundant(Foo) @@ -999,7 +973,7 @@ class Test_classImplements(_ImplementsTestMixin, unittest.TestCase): from zope.interface import ro from zope.interface.tests.test_ro import C3Setting - class Foo(object): + class Foo: pass with C3Setting(ro.C3.STRICT_IRO, False): @@ -1022,7 +996,7 @@ class Test_classImplements(_ImplementsTestMixin, unittest.TestCase): IBar = InterfaceClass('IBar') impl = Implements(IFoo) impl.declared = (IFoo,) - class Foo(object): + class Foo: __implemented__ = impl impl.inherit = Foo self._callFUT(Foo, IBar) @@ -1042,9 +1016,9 @@ class Test_classImplements(_ImplementsTestMixin, unittest.TestCase): impl_root = Implements.named('Root', IRoot) impl_root.declared = (IRoot,) - class Root1(object): + class Root1: __implemented__ = impl_root - class Root2(object): + class Root2: __implemented__ = impl_root impl_extends_root = Implements.named('ExtendsRoot1', IExtendsRoot) @@ -1086,7 +1060,7 @@ class Test__implements_advice(unittest.TestCase): from zope.interface.declarations import Implements from zope.interface.interface import InterfaceClass IFoo = InterfaceClass('IFoo') - class Foo(object): + class Foo: __implements_advice_data__ = ((IFoo,), classImplements) self._callFUT(Foo) self.assertNotIn('__implements_advice_data__', Foo.__dict__) @@ -1116,7 +1090,7 @@ class Test_implementer(Test_classImplements): def test_nonclass_can_assign_attr(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass('IFoo') - class Foo(object): + class Foo: pass foo = Foo() decorator = self._makeOne(IFoo) @@ -1140,7 +1114,7 @@ class Test_implementer(Test_classImplements): begin_count = len(gc.get_objects()) for _ in range(1900): - class TestClass(object): + class TestClass: pass self._callFUT(TestClass, IFoo) @@ -1190,118 +1164,6 @@ class Test_implementer_only(Test_classImplementsOnly): -# Test '_implements' by way of 'implements{,Only}', its only callers. - -class Test_implementsOnly(unittest.TestCase, _Py3ClassAdvice): - - def test_simple(self): - import warnings - from zope.interface.declarations import implementsOnly - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - globs = {'implementsOnly': implementsOnly, - 'IFoo': IFoo, - } - locs = {} - CODE = "\n".join([ - 'class Foo(object):' - ' implementsOnly(IFoo)', - ]) - with warnings.catch_warnings(record=True) as log: - warnings.resetwarnings() - try: - exec(CODE, globs, locs) # pylint:disable=exec-used - except TypeError: - self.assertTrue(PYTHON3, "Must be Python 3") - else: - if PYTHON3: - self.fail("Didn't raise TypeError") - Foo = locs['Foo'] - spec = Foo.__implemented__ - self.assertEqual(list(spec), [IFoo]) - self.assertEqual(len(log), 0) # no longer warn - - def test_called_once_from_class_w_bases(self): - from zope.interface.declarations import implements - from zope.interface.declarations import implementsOnly - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - IBar = InterfaceClass("IBar") - globs = {'implements': implements, - 'implementsOnly': implementsOnly, - 'IFoo': IFoo, - 'IBar': IBar, - } - locs = {} - CODE = "\n".join([ - 'class Foo(object):', - ' implements(IFoo)', - 'class Bar(Foo):' - ' implementsOnly(IBar)', - ]) - if self._run_generated_code(CODE, globs, locs): - Bar = locs['Bar'] - spec = Bar.__implemented__ - self.assertEqual(list(spec), [IBar]) - - -class Test_implements(unittest.TestCase, _Py3ClassAdvice): - - def test_called_from_function(self): - import warnings - from zope.interface.declarations import implements - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - globs = {'implements': implements, 'IFoo': IFoo} - locs = {} - CODE = "\n".join([ - 'def foo():', - ' implements(IFoo)' - ]) - if self._run_generated_code(CODE, globs, locs, False): - foo = locs['foo'] - with warnings.catch_warnings(record=True) as log: - warnings.resetwarnings() - self.assertRaises(TypeError, foo) - self.assertEqual(len(log), 0) # no longer warn - - def test_called_twice_from_class(self): - import warnings - from zope.interface.declarations import implements - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - IBar = InterfaceClass("IBar") - globs = {'implements': implements, 'IFoo': IFoo, 'IBar': IBar} - locs = {} - CODE = "\n".join([ - 'class Foo(object):', - ' implements(IFoo)', - ' implements(IBar)', - ]) - with warnings.catch_warnings(record=True) as log: - warnings.resetwarnings() - try: - exec(CODE, globs, locs) # pylint:disable=exec-used - except TypeError: - if not PYTHON3: - self.assertEqual(len(log), 0) # no longer warn - else: - self.fail("Didn't raise TypeError") - - def test_called_once_from_class(self): - from zope.interface.declarations import implements - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - globs = {'implements': implements, 'IFoo': IFoo} - locs = {} - CODE = "\n".join([ - 'class Foo(object):', - ' implements(IFoo)', - ]) - if self._run_generated_code(CODE, globs, locs): - Foo = locs['Foo'] - spec = Foo.__implemented__ - self.assertEqual(list(spec), [IFoo]) class ProvidesClassTests(unittest.TestCase): @@ -1316,7 +1178,7 @@ class ProvidesClassTests(unittest.TestCase): def test_simple_class_one_interface(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass spec = self._makeOne(Foo, IFoo) self.assertEqual(list(spec), [IFoo]) @@ -1325,7 +1187,7 @@ class ProvidesClassTests(unittest.TestCase): from zope.interface.declarations import Provides # the function from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass spec = self._makeOne(Foo, IFoo) klass, args = spec.__reduce__() @@ -1335,7 +1197,7 @@ class ProvidesClassTests(unittest.TestCase): def test___get___class(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass spec = self._makeOne(Foo, IFoo) Foo.__provides__ = spec @@ -1344,7 +1206,7 @@ class ProvidesClassTests(unittest.TestCase): def test___get___instance(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass spec = self._makeOne(Foo, IFoo) Foo.__provides__ = spec @@ -1358,7 +1220,7 @@ class ProvidesClassStrictTests(ProvidesClassTests): # Tests that require the strict C3 resolution order. def _getTargetClass(self): - ProvidesClass = super(ProvidesClassStrictTests, self)._getTargetClass() + ProvidesClass = super()._getTargetClass() class StrictProvides(ProvidesClass): def _do_calculate_ro(self, base_mros): return ProvidesClass._do_calculate_ro(self, base_mros=base_mros, strict=True) @@ -1375,7 +1237,7 @@ class ProvidesClassStrictTests(ProvidesClassTests): pass @implementer(IBase) - class Base(object): + class Base: pass spec = self._makeOne(Base, IBase) @@ -1402,7 +1264,7 @@ class TestProvidesClassRepr(unittest.TestCase): IFoo = InterfaceClass("IFoo") assert IFoo.__name__ == 'IFoo' assert IFoo.__module__ == __name__ - assert repr(IFoo) == '<InterfaceClass %s.IFoo>' % (__name__,) + assert repr(IFoo) == '<InterfaceClass {}.IFoo>'.format(__name__) IBar = InterfaceClass("IBar") @@ -1507,7 +1369,7 @@ class TestProvidesClassRepr(unittest.TestCase): class IFoo(Interface): "Does nothing" - class Bar(object): + class Bar: "Does nothing" impl = implementedBy(type(self)) @@ -1526,7 +1388,7 @@ class TestProvidesClassRepr(unittest.TestCase): ) def test__repr__non_class(self): - class Object(object): + class Object: __bases__ = () __str__ = lambda _: self.fail("Should not call str") @@ -1545,7 +1407,7 @@ class TestProvidesClassRepr(unittest.TestCase): IFoo = InterfaceClass("IFoo") @implementer(IFoo) - class Foo(object): + class Foo: pass inst = providedBy(Foo()) @@ -1563,7 +1425,7 @@ class TestProvidesClassRepr(unittest.TestCase): IBar = InterfaceClass("IBar") @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() @@ -1588,7 +1450,7 @@ class Test_Provides(unittest.TestCase): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") cache = {} - class Foo(object): + class Foo: pass with _Monkey(declarations, InstanceDeclarations=cache): spec = self._callFUT(Foo, IFoo) @@ -1600,7 +1462,7 @@ class Test_Provides(unittest.TestCase): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") prior = object() - class Foo(object): + class Foo: pass cache = {(Foo, IFoo): prior} with _Monkey(declarations, InstanceDeclarations=cache): @@ -1618,7 +1480,7 @@ class Test_directlyProvides(unittest.TestCase): from zope.interface.declarations import ProvidesClass from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass obj = Foo() self._callFUT(obj, IFoo) @@ -1629,37 +1491,18 @@ class Test_directlyProvides(unittest.TestCase): from zope.interface.declarations import ClassProvides from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass self._callFUT(Foo, IFoo) self.assertIsInstance(Foo.__provides__, ClassProvides) # pylint:disable=no-member self.assertEqual(list(Foo.__provides__), [IFoo]) # pylint:disable=no-member - @_skip_under_py3k - def test_w_non_descriptor_aware_metaclass(self): - # There are no non-descriptor-aware types in Py3k - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - class MetaClass(type): - def __getattribute__(cls, name): - # Emulate metaclass whose base is not the type object. - if name == '__class__': - return cls - # Under certain circumstances, the implementedByFallback - # can get here for __dict__ - return type.__getattribute__(cls, name) # pragma: no cover - - class Foo(object): - __metaclass__ = MetaClass - obj = Foo() - self.assertRaises(TypeError, self._callFUT, obj, IFoo) - def test_w_classless_object(self): from zope.interface.declarations import ProvidesClass from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") the_dict = {} - class Foo(object): + class Foo: def __getattribute__(self, name): # Emulate object w/o any class if name == '__class__': @@ -1683,7 +1526,7 @@ class Test_alsoProvides(unittest.TestCase): from zope.interface.declarations import ProvidesClass from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass obj = Foo() self._callFUT(obj, IFoo) @@ -1696,7 +1539,7 @@ class Test_alsoProvides(unittest.TestCase): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") IBar = InterfaceClass("IBar") - class Foo(object): + class Foo: pass obj = Foo() directlyProvides(obj, IFoo) @@ -1714,7 +1557,7 @@ class Test_noLongerProvides(unittest.TestCase): def test_wo_existing_provides(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass obj = Foo() self._callFUT(obj, IFoo) @@ -1724,7 +1567,7 @@ class Test_noLongerProvides(unittest.TestCase): from zope.interface.declarations import directlyProvides from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass obj = Foo() directlyProvides(obj, IFoo) @@ -1736,7 +1579,7 @@ class Test_noLongerProvides(unittest.TestCase): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") IBar = InterfaceClass("IBar") - class Foo(object): + class Foo: pass obj = Foo() directlyProvides(obj, IFoo) @@ -1748,7 +1591,7 @@ class Test_noLongerProvides(unittest.TestCase): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") @implementer(IFoo) - class Foo(object): + class Foo: pass obj = Foo() self.assertRaises(ValueError, self._callFUT, obj, IFoo) @@ -1773,7 +1616,7 @@ class ClassProvidesBaseFallbackTests(unittest.TestCase): def test_w_same_class_via_class(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass cpbp = Foo.__provides__ = self._makeOne(Foo, IFoo) self.assertTrue(Foo.__provides__ is cpbp) @@ -1781,7 +1624,7 @@ class ClassProvidesBaseFallbackTests(unittest.TestCase): def test_w_same_class_via_instance(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass foo = Foo() Foo.__provides__ = self._makeOne(Foo, IFoo) @@ -1790,7 +1633,7 @@ class ClassProvidesBaseFallbackTests(unittest.TestCase): def test_w_different_class(self): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass class Bar(Foo): pass @@ -1829,7 +1672,7 @@ class ClassProvidesTests(unittest.TestCase): IFoo = InterfaceClass("IFoo") IBar = InterfaceClass("IBar") @implementer(IFoo) - class Foo(object): + class Foo: pass cp = Foo.__provides__ = self._makeOne(Foo, type(Foo), IBar) self.assertTrue(Foo.__provides__ is cp) @@ -1841,7 +1684,7 @@ class ClassProvidesTests(unittest.TestCase): IFoo = InterfaceClass("IFoo") IBar = InterfaceClass("IBar") @implementer(IFoo) - class Foo(object): + class Foo: pass cp = Foo.__provides__ = self._makeOne(Foo, type(Foo), IBar) self.assertEqual(cp.__reduce__(), @@ -1852,7 +1695,7 @@ class ClassProvidesStrictTests(ClassProvidesTests): # Tests that require the strict C3 resolution order. def _getTargetClass(self): - ClassProvides = super(ClassProvidesStrictTests, self)._getTargetClass() + ClassProvides = super()._getTargetClass() class StrictClassProvides(ClassProvides): def _do_calculate_ro(self, base_mros): return ClassProvides._do_calculate_ro(self, base_mros=base_mros, strict=True) @@ -1935,7 +1778,7 @@ class TestClassProvidesRepr(unittest.TestCase): IFoo = InterfaceClass("IFoo") @implementer(IFoo) - class Foo(object): + class Foo: pass inst = implementedBy(Foo) @@ -1948,14 +1791,14 @@ class TestClassProvidesRepr(unittest.TestCase): from zope.interface.declarations import implementedBy # We can't get a __name__ by default, so we get a # module name and a question mark - class Callable(object): + class Callable: def __call__(self): return self inst = implementedBy(Callable()) self.assertEqual( repr(inst), - 'classImplements(%s.?)' % (__name__,) + 'classImplements({}.?)'.format(__name__) ) c = Callable() @@ -1974,7 +1817,7 @@ class Test_directlyProvidedBy(unittest.TestCase): return directlyProvidedBy(*args, **kw) def test_wo_declarations_in_class_or_instance(self): - class Foo(object): + class Foo: pass foo = Foo() self.assertEqual(list(self._callFUT(foo)), []) @@ -1984,7 +1827,7 @@ class Test_directlyProvidedBy(unittest.TestCase): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() self.assertEqual(list(self._callFUT(foo)), []) @@ -1993,7 +1836,7 @@ class Test_directlyProvidedBy(unittest.TestCase): from zope.interface.declarations import directlyProvides from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass foo = Foo() directlyProvides(foo, IFoo) @@ -2006,76 +1849,13 @@ class Test_directlyProvidedBy(unittest.TestCase): IFoo = InterfaceClass("IFoo") IBar = InterfaceClass("IBar") @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() directlyProvides(foo, IBar) self.assertEqual(list(self._callFUT(foo)), [IBar]) -class Test_classProvides(unittest.TestCase, _Py3ClassAdvice): - # pylint:disable=exec-used - - def test_called_from_function(self): - import warnings - from zope.interface.declarations import classProvides - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - globs = {'classProvides': classProvides, 'IFoo': IFoo} - locs = {} - CODE = "\n".join([ - 'def foo():', - ' classProvides(IFoo)' - ]) - exec(CODE, globs, locs) - foo = locs['foo'] - with warnings.catch_warnings(record=True) as log: - warnings.resetwarnings() - self.assertRaises(TypeError, foo) - if not PYTHON3: - self.assertEqual(len(log), 0) # no longer warn - - def test_called_twice_from_class(self): - import warnings - from zope.interface.declarations import classProvides - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - IBar = InterfaceClass("IBar") - globs = {'classProvides': classProvides, 'IFoo': IFoo, 'IBar': IBar} - locs = {} - CODE = "\n".join([ - 'class Foo(object):', - ' classProvides(IFoo)', - ' classProvides(IBar)', - ]) - with warnings.catch_warnings(record=True) as log: - warnings.resetwarnings() - try: - exec(CODE, globs, locs) - except TypeError: - if not PYTHON3: - self.assertEqual(len(log), 0) # no longer warn - else: - self.fail("Didn't raise TypeError") - - def test_called_once_from_class(self): - from zope.interface.declarations import classProvides - from zope.interface.interface import InterfaceClass - IFoo = InterfaceClass("IFoo") - globs = {'classProvides': classProvides, 'IFoo': IFoo} - locs = {} - CODE = "\n".join([ - 'class Foo(object):', - ' classProvides(IFoo)', - ]) - if self._run_generated_code(CODE, globs, locs): - Foo = locs['Foo'] - spec = Foo.__providedBy__ - self.assertEqual(list(spec), [IFoo]) - -# Test _classProvides_advice through classProvides, its only caller. - - class Test_provider(unittest.TestCase): def _getTargetClass(self): @@ -2090,7 +1870,7 @@ class Test_provider(unittest.TestCase): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") @self._makeOne(IFoo) - class Foo(object): + class Foo: pass self.assertIsInstance(Foo.__provides__, ClassProvides) # pylint:disable=no-member self.assertEqual(list(Foo.__provides__), [IFoo]) # pylint:disable=no-member @@ -2170,7 +1950,7 @@ class Test_getObjectSpecificationFallback(unittest.TestCase): def test_wo_existing_provides_classless(self): the_dict = {} - class Foo(object): + class Foo: def __getattribute__(self, name): # Emulate object w/o any class if name == '__class__': @@ -2206,7 +1986,7 @@ class Test_getObjectSpecificationFallback(unittest.TestCase): from zope.interface.declarations import directlyProvides from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass foo = Foo() directlyProvides(foo, IFoo) @@ -2218,14 +1998,14 @@ class Test_getObjectSpecificationFallback(unittest.TestCase): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() spec = self._callFUT(foo) self.assertEqual(list(spec), [IFoo]) def test_wo_provides_on_class_wo_implements(self): - class Foo(object): + class Foo: pass foo = Foo() spec = self._callFUT(foo) @@ -2242,7 +2022,7 @@ class Test_getObjectSpecificationFallback(unittest.TestCase): # isinstance(ob.__provides__, SpecificationBase) is not # protected inside any kind of block. - class Foo(object): + class Foo: __provides__ = MissingSomeAttrs(AttributeError) # isinstance() ignores AttributeError on __class__ @@ -2251,18 +2031,14 @@ class Test_getObjectSpecificationFallback(unittest.TestCase): def test_raises_AttributeError_when_provides_fails_type_check_RuntimeError(self): # isinstance(ob.__provides__, SpecificationBase) is not # protected inside any kind of block. - class Foo(object): + class Foo: __provides__ = MissingSomeAttrs(RuntimeError) - if PYTHON3: - with self.assertRaises(RuntimeError) as exc: - self._callFUT(Foo()) - - self.assertEqual('__class__', exc.exception.args[0]) - else: - # Python 2 catches everything. + with self.assertRaises(RuntimeError) as exc: self._callFUT(Foo()) + self.assertEqual('__class__', exc.exception.args[0]) + class Test_getObjectSpecification(Test_getObjectSpecificationFallback, OptimizationTestMixin): @@ -2286,7 +2062,7 @@ class Test_providedByFallback(unittest.TestCase): return self._getTargetClass()(*args, **kw) def test_wo_providedBy_on_class_wo_implements(self): - class Foo(object): + class Foo: pass foo = Foo() spec = self._callFUT(foo) @@ -2296,7 +2072,7 @@ class Test_providedByFallback(unittest.TestCase): from zope.interface.declarations import Provides from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass foo = Foo() foo.__providedBy__ = Provides(Foo, IFoo) @@ -2304,7 +2080,7 @@ class Test_providedByFallback(unittest.TestCase): self.assertEqual(list(spec), [IFoo]) def test_w_providedBy_invalid_spec(self): - class Foo(object): + class Foo: pass foo = Foo() foo.__providedBy__ = object() @@ -2316,7 +2092,7 @@ class Test_providedByFallback(unittest.TestCase): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() foo.__providedBy__ = object() @@ -2324,7 +2100,7 @@ class Test_providedByFallback(unittest.TestCase): self.assertEqual(list(spec), [IFoo]) def test_w_providedBy_invalid_spec_w_provides_no_provides_on_class(self): - class Foo(object): + class Foo: pass foo = Foo() foo.__providedBy__ = object() @@ -2333,7 +2109,7 @@ class Test_providedByFallback(unittest.TestCase): self.assertTrue(spec is expected) def test_w_providedBy_invalid_spec_w_provides_diff_provides_on_class(self): - class Foo(object): + class Foo: pass foo = Foo() foo.__providedBy__ = object() @@ -2347,7 +2123,7 @@ class Test_providedByFallback(unittest.TestCase): from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() foo.__providedBy__ = object() @@ -2366,7 +2142,7 @@ class Test_providedByFallback(unittest.TestCase): pass @implementer(IBase) - class Base(object): + class Base: pass @implementer(IDerived) @@ -2391,7 +2167,7 @@ class Test_providedByFallback(unittest.TestCase): class IDerived(IBase): pass - class Base(object): + class Base: pass @implementer(IDerived) @@ -2415,7 +2191,7 @@ class Test_providedByFallback(unittest.TestCase): pass @implementer(IDerived) - class Derived(object): + class Derived: pass derived = Derived() @@ -2438,7 +2214,7 @@ class Test_providedByFallback(unittest.TestCase): pass @implementer(IBase) - class Base(object): + class Base: pass class Derived(Base): @@ -2475,7 +2251,7 @@ class Test_providedByFallback(unittest.TestCase): pass @implementer(IBase) - class Base(object): + class Base: pass @implementer(IM1) @@ -2512,9 +2288,8 @@ class Test_providedByFallback(unittest.TestCase): def test_catches_only_AttributeError_on_class(self): # isinstance() tries to get the __class__, which is non-obvious, # so it must be protected too. - PY3 = str is not bytes - MissingSomeAttrs.test_raises(self, self._callFUT, - expected_missing='__class__' if PY3 else '__providedBy__') + MissingSomeAttrs.test_raises( + self, self._callFUT, expected_missing='__class__') @@ -2544,7 +2319,7 @@ class ObjectSpecificationDescriptorFallbackTests(unittest.TestCase): from zope.interface.declarations import Provides from zope.interface.interface import InterfaceClass IFoo = InterfaceClass("IFoo") - class Foo(object): + class Foo: pass Foo.__provides__ = Provides(Foo, IFoo) Foo.__providedBy__ = self._makeOne() @@ -2557,7 +2332,7 @@ class ObjectSpecificationDescriptorFallbackTests(unittest.TestCase): IFoo = InterfaceClass("IFoo") IBar = InterfaceClass("IBar") @implementer(IFoo) - class Foo(object): + class Foo: pass Foo.__provides__ = Provides(Foo, IBar) Foo.__providedBy__ = self._makeOne() @@ -2573,7 +2348,7 @@ class ObjectSpecificationDescriptorFallbackTests(unittest.TestCase): IBar = InterfaceClass("IBar") IBaz = InterfaceClass("IBaz") @implementer(IFoo) - class Foo(object): + class Foo: pass Foo.__provides__ = Provides(Foo, IBar) Foo.__providedBy__ = self._makeOne() @@ -2586,7 +2361,7 @@ class ObjectSpecificationDescriptorFallbackTests(unittest.TestCase): class MyException(Exception): pass - class Foo(object): + class Foo: __providedBy__ = self._makeOne() @property @@ -2602,7 +2377,7 @@ class ObjectSpecificationDescriptorFallbackTests(unittest.TestCase): class MyException(Exception): pass - class Foo(object): + class Foo: __providedBy__ = self._makeOne() @property @@ -2621,7 +2396,7 @@ class ObjectSpecificationDescriptorFallbackTests(unittest.TestCase): pass @implementer(IFoo) - class Foo(object): + class Foo: @property def __provides__(self): @@ -2645,7 +2420,7 @@ class ObjectSpecificationDescriptorTests( # Test _normalizeargs through its callers. -class _Monkey(object): +class _Monkey: # context-manager for replacing module names in the scope of a test. def __init__(self, module, **kw): self.module = module @@ -2661,7 +2436,7 @@ class _Monkey(object): setattr(self.module, key, value) -class _MonkeyDict(object): +class _MonkeyDict: # context-manager for restoring a dict w/in a module in the scope of a test. def __init__(self, module, attrname, **kw): self.module = module diff --git a/src/zope/interface/tests/test_exceptions.py b/src/zope/interface/tests/test_exceptions.py index ecebf91..dc22c71 100644 --- a/src/zope/interface/tests/test_exceptions.py +++ b/src/zope/interface/tests/test_exceptions.py @@ -82,7 +82,7 @@ def broken_function(): 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. """ diff --git a/src/zope/interface/tests/test_interface.py b/src/zope/interface/tests/test_interface.py index 00c3597..b3a440e 100644 --- a/src/zope/interface/tests/test_interface.py +++ b/src/zope/interface/tests/test_interface.py @@ -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 @@ class Test_invariant(unittest.TestCase): def _check(*args, **kw): raise NotImplementedError() - class Foo(object): + class Foo: invariant(_check) self.assertEqual(getattr(Foo, TAGGED_DATA, None), @@ -56,7 +55,7 @@ class Test_invariant(unittest.TestCase): def _another_check(*args, **kw): raise NotImplementedError() - class Foo(object): + class Foo: invariant(_check) invariant(_another_check) @@ -70,7 +69,7 @@ class Test_taggedValue(unittest.TestCase): 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 @@ class Test_taggedValue(unittest.TestCase): 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 @@ class Test_taggedValue(unittest.TestCase): 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 @@ class SpecificationBasePyTests(GenericSpecificationBaseTests): 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 @@ class SpecificationBasePyTests(GenericSpecificationBaseTests): 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 @@ class NameAndModuleComparisonTestsMixin(CleanUp): # 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 @@ class NameAndModuleComparisonTestsMixin(CleanUp): 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 @@ class InterfaceBaseTestsMixin(NameAndModuleComparisonTestsMixin): 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 @@ class InterfaceBasePyTests(InterfaceBaseTestsMixin, unittest.TestCase): 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 SpecificationTests(unittest.TestCase): class IDefaultViewName(Interface): pass - class Context(object): + class Context: pass class RDBModel(Context): @@ -584,7 +583,7 @@ class SpecificationTests(unittest.TestCase): pass @implementer(IOther) - class OtherBase(object): + class OtherBase: pass class Model(OtherBase, Context): @@ -1035,8 +1034,8 @@ class InterfaceClassTests(unittest.TestCase): 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 @@ class InterfaceClassTests(unittest.TestCase): 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 InterfaceTests(unittest.TestCase): class IOther(Interface): pass - class Current(object): + class Current: __implemented__ = ICurrent def method1(self, a, b): raise NotImplementedError() @@ -1235,7 +1232,7 @@ class InterfaceTests(unittest.TestCase): class IDerived(IBase): pass - class Current(object): + class Current: __implemented__ = IDerived def method(self): raise NotImplementedError() @@ -1263,13 +1260,13 @@ class InterfaceTests(unittest.TestCase): 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 @@ class InterfaceTests(unittest.TestCase): 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 InterfaceTests(unittest.TestCase): class ICheckMe(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "A method" - class CheckMe(object): + class CheckMe: __implemented__ = ICheckMe attr = 'value' @@ -1372,12 +1369,12 @@ class InterfaceTests(unittest.TestCase): class ICheckMe(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "A method" - class CheckMe(object): + class CheckMe: __implemented__ = ICheckMe attr = 'value' @@ -1402,7 +1399,7 @@ class InterfaceTests(unittest.TestCase): class ISimple(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): """docstring""" @@ -1415,13 +1412,13 @@ class InterfaceTests(unittest.TestCase): class IBase(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): """docstring""" class IDerived(IBase): - attr2 = Attribute(u'My attr2') + attr2 = Attribute('My attr2') def method(): """docstring""" @@ -1441,7 +1438,7 @@ class InterfaceTests(unittest.TestCase): class ISimple(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" @@ -1465,13 +1462,13 @@ class InterfaceTests(unittest.TestCase): class IBase(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" class IDerived(IBase): - attr2 = Attribute(u'My attr2') + attr2 = Attribute('My attr2') def method(): "My method, overridden" @@ -1530,7 +1527,7 @@ class InterfaceTests(unittest.TestCase): class ISimple(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" @@ -1552,13 +1549,13 @@ class InterfaceTests(unittest.TestCase): class IBase(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" class IDerived(IBase): - attr2 = Attribute(u'My attr2') + attr2 = Attribute('My attr2') def method(): "My method, overridden" @@ -1601,7 +1598,7 @@ class InterfaceTests(unittest.TestCase): class ISimple(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" @@ -1623,13 +1620,13 @@ class InterfaceTests(unittest.TestCase): class IBase(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" class IDerived(IBase): - attr2 = Attribute(u'My attr2') + attr2 = Attribute('My attr2') def method(): "My method, overridden" @@ -1671,7 +1668,7 @@ class InterfaceTests(unittest.TestCase): class ISimple(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" @@ -1685,13 +1682,13 @@ class InterfaceTests(unittest.TestCase): class IBase(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" class IDerived(IBase): - attr2 = Attribute(u'My attr2') + attr2 = Attribute('My attr2') def method(): "My method, overridden" @@ -1718,7 +1715,7 @@ class InterfaceTests(unittest.TestCase): class ISimple(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" @@ -1731,13 +1728,13 @@ class InterfaceTests(unittest.TestCase): class IBase(Interface): - attr = Attribute(u'My attr') + attr = Attribute('My attr') def method(): "My method" class IDerived(IBase): - attr2 = Attribute(u'My attr2') + attr2 = Attribute('My attr2') def method(): "My method, overridden" @@ -1806,7 +1803,7 @@ class InterfaceTests(unittest.TestCase): bar = Attribute('bar; must eval to Boolean True if foo does') invariant(_ifFooThenBar) - class HasInvariant(object): + class HasInvariant: pass # set up @@ -1839,7 +1836,7 @@ class InterfaceTests(unittest.TestCase): class ISubInvariant(IInvariant): invariant(_barGreaterThanFoo) - class HasInvariant(object): + class HasInvariant: pass # nested interfaces with invariants: @@ -1883,7 +1880,7 @@ class InterfaceTests(unittest.TestCase): bar = Attribute('bar; must eval to Boolean True if foo does') invariant(_ifFooThenBar) - class HasInvariant(object): + class HasInvariant: pass # now we'll do two invariants on the same interface, @@ -1942,21 +1939,6 @@ class InterfaceTests(unittest.TestCase): self.assertEqual(IDocstringAndAttribute.__doc__, "") self.assertEqual(list(IDocstringAndAttribute), ['__doc__']) - @_skip_under_py3k - def testIssue228(self): - # Test for http://collector.zope.org/Zope3-dev/228 - # Old style classes don't have a '__class__' attribute - # No old style classes in Python 3, so the test becomes moot. - from zope.interface import Interface - - class I(Interface): - "xxx" - - class OldStyle: - __providedBy__ = None - - self.assertRaises(AttributeError, I.providedBy, OldStyle) - def test_invariant_as_decorator(self): from zope.interface import Interface from zope.interface import Attribute @@ -1974,7 +1956,7 @@ class InterfaceTests(unittest.TestCase): raise Invalid('max < min') @implementer(IRange) - class Range(object): + class Range: def __init__(self, min, max): self.min, self.max = min, max @@ -2009,7 +1991,7 @@ class InterfaceTests(unittest.TestCase): self.assertEqual(IDerived2.getTaggedValue('qux'), 'Spam Spam') self.assertEqual(IDerived2.getTaggedValue('foo'), 'bar') - self.assertEqual(set(IDerived2.getTaggedValueTags()), set(['qux', 'foo'])) + self.assertEqual(set(IDerived2.getTaggedValueTags()), {'qux', 'foo'}) def _make_taggedValue_tree(self, base): from zope.interface import taggedValue @@ -2106,7 +2088,7 @@ class InterfaceTests(unittest.TestCase): pass @implementer(I) - class C(object): + class C: def __conform__(self, proto): return 0 @@ -2120,7 +2102,7 @@ class InterfaceTests(unittest.TestCase): pass @implementer(I) - class C(object): + class C: pass c = C() @@ -2132,7 +2114,7 @@ class InterfaceTests(unittest.TestCase): class I(Interface): pass - class C(object): + class C: pass c = C() @@ -2144,7 +2126,7 @@ class InterfaceTests(unittest.TestCase): class I(Interface): pass - class C(object): + class C: pass c = C() @@ -2163,7 +2145,7 @@ class InterfaceTests(unittest.TestCase): class I(Interface): pass - class C(object): + class C: pass c = C() @@ -2187,7 +2169,7 @@ class InterfaceTests(unittest.TestCase): return 42 @implementer(I) - class O(object): + class O: pass self.assertEqual(42, I(object())) @@ -2211,12 +2193,12 @@ class InterfaceTests(unittest.TestCase): """Nothing special.""" @implementer(IAdapt) - class Conform24(object): + class Conform24: def __conform__(self, iface): return 24 @implementer(IAdapt) - class ConformNone(object): + class ConformNone: def __conform__(self, iface): return None @@ -2243,14 +2225,10 @@ class InterfaceTests(unittest.TestCase): def __adapt__(self, obj): if not self.providedBy(obj): return 42 - if sys.version_info[:2] > (3, 5): - # Python 3.5 raises 'RuntimeError: super() __class__ is not a type' - return super().__adapt__(obj) - - return super(type(I), self).__adapt__(obj) + return super().__adapt__(obj) @implementer(I) - class O(object): + class O: pass self.assertEqual(42, I(object())) @@ -2575,7 +2553,7 @@ class Test_fromMethod(unittest.TestCase): return fromMethod(*args, **kw) def test_no_args(self): - class Foo(object): + class Foo: def bar(self): "DOCSTRING" method = self._callFUT(Foo.bar) @@ -2591,7 +2569,7 @@ class Test_fromMethod(unittest.TestCase): self.assertEqual(info['kwargs'], None) def test_full_spectrum(self): - class Foo(object): + class Foo: def bar(self, foo, bar='baz', *args, **kw): # pylint:disable=keyword-arg-before-vararg "DOCSTRING" method = self._callFUT(Foo.bar) @@ -2617,7 +2595,7 @@ class Test_fromMethod(unittest.TestCase): self.assertEqual(info['varargs'], None) self.assertEqual(info['kwargs'], None) -class DummyDependent(object): +class DummyDependent: def __init__(self): self._changed = [] @@ -2644,7 +2622,7 @@ def _ifFooThenBar(obj): raise Invalid('If Foo, then Bar!') -class _Monkey(object): +class _Monkey: # context-manager for replacing module names in the scope of a test. def __init__(self, module, **kw): self.module = module diff --git a/src/zope/interface/tests/test_interfaces.py b/src/zope/interface/tests/test_interfaces.py index 3f9a504..11ba0c0 100644 --- a/src/zope/interface/tests/test_interfaces.py +++ b/src/zope/interface/tests/test_interfaces.py @@ -1,7 +1,7 @@ import unittest -class _ConformsToIObjectEvent(object): +class _ConformsToIObjectEvent: def _makeOne(self, target=None): if target is None: diff --git a/src/zope/interface/tests/test_odd_declarations.py b/src/zope/interface/tests/test_odd_declarations.py index bdede33..5508915 100644 --- a/src/zope/interface/tests/test_odd_declarations.py +++ b/src/zope/interface/tests/test_odd_declarations.py @@ -27,7 +27,6 @@ from zope.interface import directlyProvidedBy 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 I31(I3): pass class I4(Interface): pass class I5(Interface): pass -class Odd(object): +class Odd: pass Odd = odd.MetaClass('Odd', Odd.__bases__, {}) @@ -186,10 +185,6 @@ class Test(unittest.TestCase): 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 @@ class Test(unittest.TestCase): # 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 @@ class Test(unittest.TestCase): 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__) diff --git a/src/zope/interface/tests/test_registry.py b/src/zope/interface/tests/test_registry.py index 81bb58a..eaaabb2 100644 --- a/src/zope/interface/tests/test_registry.py +++ b/src/zope/interface/tests/test_registry.py @@ -83,16 +83,16 @@ class ComponentsTests(unittest.TestCase): 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_registrations[ifoo, u'foo'], + comp._utility_registrations[ifoo, 'foo'], (foo, _info, None)) def test_registerUtility_both_factory_and_component(self): @@ -111,8 +111,8 @@ class ComponentsTests(unittest.TestCase): 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 ComponentsTests(unittest.TestCase): 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 @@ class ComponentsTests(unittest.TestCase): 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 ComponentsTests(unittest.TestCase): 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 ComponentsTests(unittest.TestCase): 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 ComponentsTests(unittest.TestCase): 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 @@ class ComponentsTests(unittest.TestCase): self.assertEqual(len(_events), 2) # unreg, reg self.assertEqual(comp._utility_registrations[(ifoo, _name)], (_to_reg, _info2, None)) # replaced - self.assertEqual(comp.utilities._subscribers[0][ifoo][u''], + self.assertEqual(comp.utilities._subscribers[0][ifoo][''], (_to_reg,)) def test_registerUtility_w_different_names_same_component(self): @@ -251,9 +251,9 @@ class ComponentsTests(unittest.TestCase): 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 @@ class ComponentsTests(unittest.TestCase): (_other_reg, _info, None)) self.assertEqual(comp._utility_registrations[(ifoo, _name2)], (_to_reg, _info, None)) - self.assertEqual(comp.utilities._subscribers[0][ifoo][u''], + self.assertEqual(comp.utilities._subscribers[0][ifoo][''], (_other_reg, _to_reg,)) def test_registerUtility_replaces_existing_reg(self): @@ -278,8 +278,8 @@ class ComponentsTests(unittest.TestCase): 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 ComponentsTests(unittest.TestCase): 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 ComponentsTests(unittest.TestCase): 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 @@ class ComponentsTests(unittest.TestCase): 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 @@ class ComponentsTests(unittest.TestCase): 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 ComponentsTests(unittest.TestCase): 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 ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _name = u'name' + _name = 'name' _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name) @@ -462,8 +462,8 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' _to_reg = object() def _factory(): return _to_reg @@ -493,11 +493,11 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass - class Foo(object): + class Foo: pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' _to_reg = Foo() directlyProvides(_to_reg, ifoo) comp = self._makeOne() @@ -527,11 +527,11 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass - class Foo(object): + class Foo: pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' _to_reg = Foo() directlyProvides(_to_reg, ifoo) comp = self._makeOne() @@ -560,9 +560,9 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) @@ -578,9 +578,9 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' _to_reg = dict() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) @@ -599,9 +599,9 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' _to_reg = dict() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) @@ -620,9 +620,9 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' _to_reg = dict() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) @@ -645,9 +645,9 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' _other_reg = object() _to_reg = object() comp = self._makeOne() @@ -665,9 +665,9 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' # First register something hashable _other_reg = object() # Then it transfers to something unhashable @@ -692,9 +692,9 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) @@ -776,8 +776,8 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _name1 = u'name1' - _name2 = u'name2' + _name1 = 'name1' + _name2 = 'name2' _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, name=_name1) @@ -799,8 +799,8 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _name1 = u'name1' - _name2 = u'name2' + _name1 = 'name1' + _name2 = 'name2' _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, name=_name1) @@ -817,16 +817,16 @@ class ComponentsTests(unittest.TestCase): ifoo = IFoo('IFoo') ibar = IFoo('IBar') - @named(u'foo') - class Foo(object): + @named('foo') + class Foo: pass - _info = u'info' + _info = 'info' comp = self._makeOne() comp.registerAdapter(Foo, (ibar,), ifoo, info=_info) self.assertEqual( - comp._adapter_registrations[(ibar,), ifoo, u'foo'], + comp._adapter_registrations[(ibar,), ifoo, 'foo'], (Foo, _info)) def test_registerAdapter_w_explicit_provided_and_required(self): @@ -838,8 +838,8 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' def _factory(context): raise NotImplementedError() @@ -871,10 +871,10 @@ class ComponentsTests(unittest.TestCase): pass ibar = IFoo('IBar') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -891,12 +891,12 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' _to_reg = object() @implementer(ifoo) - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -927,9 +927,9 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' - class _Factory(object): + _info = 'info' + _name = 'name' + class _Factory: pass comp = self._makeOne() @@ -943,9 +943,9 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _name = u'name' - class _Factory(object): + _info = 'info' + _name = 'name' + class _Factory: pass comp = self._makeOne() self.assertRaises(TypeError, comp.registerAdapter, _Factory, @@ -960,9 +960,9 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' - class _Factory(object): + _info = 'info' + _name = 'name' + class _Factory: pass comp = self._makeOne() _monkey, _events = self._wrapEvents() @@ -997,13 +997,13 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _name = u'name' - class _Factory(object): + _info = 'info' + _name = 'name' + class _Factory: pass @implementer(ibar) - class _Context(object): + class _Context: pass _ctx_impl = implementedBy(_Context) comp = self._makeOne() @@ -1035,9 +1035,9 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') - _info = u'info' - _name = u'name' - class _Factory(object): + _info = 'info' + _name = 'name' + class _Factory: pass comp = self._makeOne() self.assertRaises(TypeError, comp.registerAdapter, _Factory, [object()], @@ -1052,9 +1052,9 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _name = u'name' - class _Factory(object): + _info = 'info' + _name = 'name' + class _Factory: __component_adapts__ = (ibar,) comp = self._makeOne() @@ -1086,8 +1086,8 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _name = u'name' + _info = 'info' + _name = 'name' def _factory(context): raise NotImplementedError() @@ -1118,7 +1118,7 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -1135,7 +1135,7 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -1169,7 +1169,7 @@ class ComponentsTests(unittest.TestCase): ifoo = IFoo('IFoo') ibar = IFoo('IBar') @implementer(ifoo) - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -1199,7 +1199,7 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: __component_adapts__ = (ibar,) comp = self._makeOne() @@ -1233,10 +1233,10 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IFoo') - _info = u'info' - _name1 = u'name1' - _name2 = u'name2' - class _Factory(object): + _info = 'info' + _name1 = 'name1' + _name2 = 'name2' + class _Factory: pass comp = self._makeOne() @@ -1286,11 +1286,11 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: def __init__(self, context): self.context = context @implementer(ibar) - class _Context(object): + class _Context: pass _context = _Context() comp = self._makeOne() @@ -1308,7 +1308,7 @@ class ComponentsTests(unittest.TestCase): ifoo = IFoo('IFoo') ibar = IFoo('IBar') @implementer(ibar) - class _Context(object): + class _Context: pass _context = _Context() comp = self._makeOne() @@ -1322,11 +1322,11 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: def __init__(self, context): self.context = context @implementer(ibar) - class _Context(object): + class _Context: pass _context = _Context() comp = self._makeOne() @@ -1349,18 +1349,18 @@ class ComponentsTests(unittest.TestCase): pass @implementer(IBase) - class Base(object): + class Base: pass @implementer(IDerived) class Derived(Base): pass - class AdapterBase(object): + class AdapterBase: def __init__(self, context): self.context = context - class AdapterDerived(object): + class AdapterDerived: def __init__(self, context): self.context = context @@ -1392,7 +1392,7 @@ class ComponentsTests(unittest.TestCase): class IFoo(Interface): pass - class Base(object): + class Base: pass class Child1(Base): @@ -1406,11 +1406,11 @@ class ComponentsTests(unittest.TestCase): class Derived(Child1, Child2): pass - class AdapterBase(object): + class AdapterBase: def __init__(self, context): self.context = context - class AdapterDerived(object): + class AdapterDerived: def __init__(self, context): self.context = context @@ -1438,10 +1438,10 @@ class ComponentsTests(unittest.TestCase): ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() @@ -1458,10 +1458,10 @@ class ComponentsTests(unittest.TestCase): ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() @@ -1480,14 +1480,14 @@ class ComponentsTests(unittest.TestCase): ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() - class _Factory(object): + class _Factory: def __init__(self, context1, context2): self.context = context1, context2 comp = self._makeOne() @@ -1506,10 +1506,10 @@ class ComponentsTests(unittest.TestCase): ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() @@ -1526,14 +1526,14 @@ class ComponentsTests(unittest.TestCase): ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() - class _Factory(object): + class _Factory: def __init__(self, context1, context2): self.context = context1, context2 comp = self._makeOne() @@ -1566,14 +1566,14 @@ class ComponentsTests(unittest.TestCase): pass @implementer(IBase) - class Base(object): + class Base: pass @implementer(IDerived) class Derived(Base): pass - class AdapterBase(object): + class AdapterBase: def __init__(self, context1, context2): self.context1 = context1 self.context2 = context2 @@ -1608,10 +1608,10 @@ class ComponentsTests(unittest.TestCase): ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() @@ -1628,10 +1628,10 @@ class ComponentsTests(unittest.TestCase): ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() @@ -1655,21 +1655,21 @@ class ComponentsTests(unittest.TestCase): ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) - class _Context1(object): + class _Context1: pass @implementer(ibaz) - class _Context2(object): + class _Context2: pass _context1 = _Context1() _context2 = _Context2() - class _Factory1(object): + class _Factory1: def __init__(self, context1, context2): self.context = context1, context2 - class _Factory2(object): + class _Factory2: def __init__(self, context1, context2): self.context = context1, context2 - _name1 = u'name1' - _name2 = u'name2' + _name1 = 'name1' + _name2 = 'name2' comp = self._makeOne() comp.registerAdapter(_Factory1, (ibar, ibaz), ifoo, name=_name1) comp.registerAdapter(_Factory2, (ibar, ibaz), ifoo, name=_name2) @@ -1687,8 +1687,8 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _name = u'name' - _info = u'info' + _name = 'name' + _info = 'info' def _factory(context): raise NotImplementedError() @@ -1705,8 +1705,8 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _blank = u'' - _info = u'info' + _blank = '' + _info = 'info' def _factory(context): raise NotImplementedError() comp = self._makeOne() @@ -1742,11 +1742,11 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _blank = u'' + _info = 'info' + _blank = '' @implementer(ifoo) - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -1780,9 +1780,9 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _info = u'info' - _blank = u'' - class _Factory(object): + _info = 'info' + _blank = '' + class _Factory: __component_adapts__ = (ibar,) comp = self._makeOne() @@ -1815,8 +1815,8 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _blank = u'' - _info = u'info' + _blank = '' + _info = 'info' def _factory(context): raise NotImplementedError() @@ -1840,9 +1840,9 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IFoo') - _info = u'info' - _blank = u'' - class _Factory(object): + _info = 'info' + _blank = '' + class _Factory: pass comp = self._makeOne() @@ -1872,7 +1872,7 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - _nonblank = u'nonblank' + _nonblank = 'nonblank' comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterSubscriptionAdapter, required=ifoo, provided=ibar, name=_nonblank) @@ -1897,7 +1897,7 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -1915,7 +1915,7 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -1947,7 +1947,7 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -1981,7 +1981,7 @@ class ComponentsTests(unittest.TestCase): ifoo = IFoo('IFoo') ibar = IFoo('IBar') @implementer(ifoo) - class _Factory(object): + class _Factory: pass comp = self._makeOne() @@ -2011,7 +2011,7 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: __component_adapts__ = (ibar,) comp = self._makeOne() @@ -2042,7 +2042,7 @@ class ComponentsTests(unittest.TestCase): ibar = IFoo('IBar') comp = self._makeOne() @implementer(ibar) - class Bar(object): + class Bar: pass bar = Bar() self.assertEqual(list(comp.subscribers((bar,), ifoo)), []) @@ -2054,7 +2054,7 @@ class ComponentsTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Factory(object): + class _Factory: __component_adapts__ = (ibar,) def __init__(self, context): self._context = context @@ -2064,7 +2064,7 @@ class ComponentsTests(unittest.TestCase): comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo) comp.registerSubscriptionAdapter(_Derived, (ibar,), ifoo) @implementer(ibar) - class Bar(object): + class Bar: pass bar = Bar() subscribers = comp.subscribers((bar,), ifoo) @@ -2081,7 +2081,7 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _nonblank = u'nonblank' + _nonblank = 'nonblank' comp = self._makeOne() def _factory(context): raise NotImplementedError() @@ -2097,8 +2097,8 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _blank = u'' - _info = u'info' + _blank = '' + _info = 'info' def _factory(context): raise NotImplementedError() @@ -2129,9 +2129,9 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _info = u'info' - _blank = u'' - class _Factory(object): + _info = 'info' + _blank = '' + class _Factory: __component_adapts__ = (ifoo,) pass @@ -2184,7 +2184,7 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - _nonblank = u'nonblank' + _nonblank = 'nonblank' comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterHandler, required=(ifoo,), name=_nonblank) @@ -2263,7 +2263,7 @@ class ComponentsTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - class _Factory(object): + class _Factory: __component_adapts__ = (ifoo,) comp = self._makeOne() @@ -2292,7 +2292,7 @@ class ComponentsTests(unittest.TestCase): ifoo = IFoo('IFoo') comp = self._makeOne() @implementer(ifoo) - class Bar(object): + class Bar: pass bar = Bar() comp.handle((bar,)) # doesn't raise @@ -2313,7 +2313,7 @@ class ComponentsTests(unittest.TestCase): comp.registerHandler(_factory_1, (ifoo,)) comp.registerHandler(_factory_2, (ifoo,)) @implementer(ifoo) - class Bar(object): + class Bar: pass bar = Bar() comp.handle(bar) @@ -2355,13 +2355,13 @@ class ComponentsTests(unittest.TestCase): class IFoo(Interface): "Does nothing" - class UtilityImplementingFoo(object): + class UtilityImplementingFoo: "Does nothing" comps = self._makeOne() for i in range(30): - comps.registerUtility(UtilityImplementingFoo(), IFoo, name=u'%s' % (i,)) + comps.registerUtility(UtilityImplementingFoo(), IFoo, name='{}'.format(i)) orig_generation = comps.utilities._generation @@ -2374,14 +2374,14 @@ class ComponentsTests(unittest.TestCase): self.assertEqual(len(orig_subscribers), 1) self.assertEqual(len(orig_subscribers[0]), 1) self.assertEqual(len(orig_subscribers[0][IFoo]), 1) - self.assertEqual(len(orig_subscribers[0][IFoo][u'']), 30) + self.assertEqual(len(orig_subscribers[0][IFoo]['']), 30) # Blow a bunch of them away, creating artificial corruption new_adapters = comps.utilities._adapters = type(orig_adapters)() new_adapters.append({}) d = new_adapters[0][IFoo] = {} for name in range(10): - name = type(u'')(str(name)) + name = str(str(name)) d[name] = orig_adapters[0][IFoo][name] self.assertNotEqual(orig_adapters, new_adapters) @@ -2389,12 +2389,12 @@ class ComponentsTests(unittest.TestCase): new_subscribers = comps.utilities._subscribers = type(orig_subscribers)() new_subscribers.append({}) d = new_subscribers[0][IFoo] = {} - d[u''] = () + d[''] = () for name in range(5, 12): # 12 - 5 = 7 - name = type(u'')(str(name)) + name = str(str(name)) comp = orig_adapters[0][IFoo][name] - d[u''] += (comp,) + d[''] += (comp,) # We can preflight (by default) and nothing changes rebuild_results_preflight = comps.rebuildUtilityRegistryFromLocalCache() @@ -2417,11 +2417,11 @@ class ComponentsTests(unittest.TestCase): self.assertEqual(rebuild_results_preflight, rebuild_results) self.assertEqual(new_adapters, orig_adapters) self.assertEqual( - len(new_subscribers[0][IFoo][u'']), - len(orig_subscribers[0][IFoo][u''])) + len(new_subscribers[0][IFoo]['']), + len(orig_subscribers[0][IFoo][''])) - for orig_subscriber in orig_subscribers[0][IFoo][u'']: - self.assertIn(orig_subscriber, new_subscribers[0][IFoo][u'']) + for orig_subscriber in orig_subscribers[0][IFoo]['']: + self.assertIn(orig_subscriber, new_subscribers[0][IFoo]['']) # Preflighting, rebuilding again produce no changes. preflight_after = comps.rebuildUtilityRegistryFromLocalCache() @@ -2464,11 +2464,11 @@ class UtilityRegistrationTests(unittest.TestCase): pass ifoo = InterfaceClassSubclass('IFoo') - class _Registry(object): + class _Registry: def __repr__(self): return '_REGISTRY' registry = _Registry() - name = u'name' + name = 'name' doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, ifoo, name, component, doc, factory), @@ -2488,7 +2488,7 @@ class UtilityRegistrationTests(unittest.TestCase): verifyObject(IUtilityRegistration, ur) def test___repr__(self): - class _Component(object): + class _Component: __name__ = 'TEST' _component = _Component() ur, _registry, _name = self._makeOne(_component) @@ -2497,7 +2497,7 @@ class UtilityRegistrationTests(unittest.TestCase): % (_name)) def test___repr___provided_wo_name(self): - class _Component(object): + class _Component: def __repr__(self): return 'TEST' _component = _Component() @@ -2508,7 +2508,7 @@ class UtilityRegistrationTests(unittest.TestCase): % (_name)) def test___repr___component_wo_name(self): - class _Component(object): + class _Component: def __repr__(self): return 'TEST' _component = _Component() @@ -2650,11 +2650,11 @@ class AdapterRegistrationTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Registry(object): + class _Registry: def __repr__(self): return '_REGISTRY' registry = _Registry() - name = u'name' + name = 'name' doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, (ibar,), ifoo, name, component, doc), @@ -2674,7 +2674,7 @@ class AdapterRegistrationTests(unittest.TestCase): verifyObject(IAdapterRegistration, ar) def test___repr__(self): - class _Component(object): + class _Component: __name__ = 'TEST' _component = _Component() ar, _registry, _name = self._makeOne(_component) @@ -2683,7 +2683,7 @@ class AdapterRegistrationTests(unittest.TestCase): + "'DOCSTRING')") % (_name)) def test___repr___provided_wo_name(self): - class _Component(object): + class _Component: def __repr__(self): return 'TEST' _component = _Component() @@ -2694,7 +2694,7 @@ class AdapterRegistrationTests(unittest.TestCase): + "'DOCSTRING')") % (_name)) def test___repr___component_wo_name(self): - class _Component(object): + class _Component: def __repr__(self): return 'TEST' _component = _Component() @@ -2859,11 +2859,11 @@ class SubscriptionRegistrationTests(unittest.TestCase): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') - class _Registry(object): + class _Registry: def __repr__(self): # pragma: no cover return '_REGISTRY' registry = _Registry() - name = u'name' + name = 'name' doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, (ibar,), ifoo, name, component, doc), @@ -2895,11 +2895,11 @@ class HandlerRegistrationTests(unittest.TestCase): class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') - class _Registry(object): + class _Registry: def __repr__(self): return '_REGISTRY' registry = _Registry() - name = u'name' + name = 'name' doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, (ifoo,), name, component, doc), @@ -2927,7 +2927,7 @@ class HandlerRegistrationTests(unittest.TestCase): self.assertTrue(hr.provided is None) def test___repr___factory_w_name(self): - class _Factory(object): + class _Factory: __name__ = 'TEST' hr, _registry, _name = self._makeOne(_Factory()) self.assertEqual(repr(hr), @@ -2935,7 +2935,7 @@ class HandlerRegistrationTests(unittest.TestCase): + "'DOCSTRING')") % (_name)) def test___repr___factory_wo_name(self): - class _Factory(object): + class _Factory: def __repr__(self): return 'TEST' hr, _registry, _name = self._makeOne(_Factory()) @@ -3041,11 +3041,11 @@ class TestPersistentComponentsDict(TestPersistentDictComponents): def _getTargetClass(self): return PersistentComponentsDict -class _Monkey(object): +class _Monkey: # context-manager for replacing module names in the scope of a test. def __init__(self, module, **kw): self.module = module - self.to_restore = dict([(key, getattr(module, key)) for key in kw]) + self.to_restore = {key: getattr(module, key) for key in kw} for key, value in kw.items(): setattr(module, key, value) diff --git a/src/zope/interface/tests/test_ro.py b/src/zope/interface/tests/test_ro.py index 81b1b71..6f7a644 100644 --- a/src/zope/interface/tests/test_ro.py +++ b/src/zope/interface/tests/test_ro.py @@ -47,26 +47,26 @@ class Test__flatten(unittest.TestCase): 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 @@ class Test_ro(unittest.TestCase): 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 @@ class Test_ro(unittest.TestCase): 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 @@ class Test_ro(unittest.TestCase): 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 @@ class Test_ro(unittest.TestCase): implementedBy(object)]) -class C3Setting(object): +class C3Setting: def __init__(self, setting, value): self._setting = setting @@ -277,7 +277,7 @@ Object <InterfaceClass zope.interface.tests.test_ro.A> has different legacy and # 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): @@ -337,9 +337,6 @@ Object <InterfaceClass zope.interface.tests.test_ro.A> has different legacy and 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 @@ -367,7 +364,7 @@ Object <InterfaceClass zope.interface.tests.test_ro.A> has different legacy and 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): @@ -407,7 +404,7 @@ class TestC3(unittest.TestCase): class Test_ROComparison(unittest.TestCase): - class MockC3(object): + class MockC3: direct_inconsistency = False bases_had_inconsistency = False diff --git a/src/zope/interface/tests/test_verify.py b/src/zope/interface/tests/test_verify.py index 5bceef6..5227a92 100644 --- a/src/zope/interface/tests/test_verify.py +++ b/src/zope/interface/tests/test_verify.py @@ -43,7 +43,7 @@ class Test_verifyClass(unittest.TestCase): class ICurrent(Interface): pass - class Current(object): + class Current: pass self.assertRaises(DoesNotImplement, self._callFUT, ICurrent, Current) @@ -55,7 +55,7 @@ class Test_verifyClass(unittest.TestCase): class ICurrent(Interface): pass - class Current(object): + class Current: pass classImplements(Current, ICurrent) @@ -72,7 +72,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: pass self.assertRaises(BrokenImplementation, @@ -87,7 +87,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self): raise NotImplementedError() @@ -107,7 +107,7 @@ class Test_verifyClass(unittest.TestCase): pass @implementer(IDerived) - class Current(object): + class Current: pass self.assertRaises(BrokenImplementation, @@ -125,7 +125,7 @@ class Test_verifyClass(unittest.TestCase): pass @implementer(IDerived) - class Current(object): + class Current: def method(self): raise NotImplementedError() @@ -143,7 +143,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, b): raise NotImplementedError() @@ -161,7 +161,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self): raise NotImplementedError() @@ -180,7 +180,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self): raise NotImplementedError() @@ -199,7 +199,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self): raise NotImplementedError() @@ -218,7 +218,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a, b): raise NotImplementedError() @@ -236,7 +236,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a, b=None): raise NotImplementedError() @@ -253,7 +253,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, *args): raise NotImplementedError() @@ -271,7 +271,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, **kw): raise NotImplementedError() @@ -289,7 +289,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a, *args): raise NotImplementedError() @@ -306,7 +306,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a, *args, **kw): raise NotImplementedError() @@ -324,7 +324,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a): raise NotImplementedError() @@ -342,7 +342,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a, *args): raise NotImplementedError() @@ -359,7 +359,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, *args): raise NotImplementedError() @@ -376,7 +376,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, **kw): raise NotImplementedError() @@ -394,7 +394,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a, *args): raise NotImplementedError() @@ -414,7 +414,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: def method(self, a): raise NotImplementedError() @@ -494,7 +494,7 @@ class Test_verifyClass(unittest.TestCase): def __call__(self, *args, **kw): raise NotImplementedError() - class QuasiCallable(object): + class QuasiCallable: def __call__(self, *args, **kw): raise NotImplementedError() @@ -522,7 +522,7 @@ class Test_verifyClass(unittest.TestCase): """docstring""" @implementer(ICurrent) - class Current(object): + class Current: @decorator def method(self, a): @@ -564,7 +564,7 @@ class Test_verifyClass(unittest.TestCase): def meth2(arg1): "Method 2" - class SeveralMethods(object): + class SeveralMethods: pass with self.assertRaises(MultipleInvalid) as exc: @@ -642,7 +642,7 @@ class Test_verifyObject(Test_verifyClass): "The bar method" @provider(IFoo) - class Foo(object): + class Foo: @staticmethod def bar(a, b): diff --git a/src/zope/interface/verify.py b/src/zope/interface/verify.py index 0a64aeb..0ab0b3f 100644 --- a/src/zope/interface/verify.py +++ b/src/zope/interface/verify.py @@ -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 @@ def _verify_element(iface, name, desc, candidate, vtype): # 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 @@ def _verify_element(iface, name, desc, candidate, vtype): return if isinstance(attr, FunctionType): - if sys.version_info[0] >= 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 @@ def _verify_element(iface, name, desc, candidate, vtype): # 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 @@ def verifyObject(iface, candidate, tentative=False): 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'] != @@ -4,15 +4,11 @@ minversion = 3.18 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 pypy3 docs coverage @@ -22,11 +18,11 @@ usedevelop = true deps = 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 +40,7 @@ commands = 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] |