Script 'mail_helper' called by obssrc Hello community, here is the log from the commit of package python-decorator for openSUSE:Factory checked in at 2026-12-01 16:58:08 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Comparing /work/SRC/openSUSE:Factory/python-decorator (Old) and /work/SRC/openSUSE:Factory/.python-decorator.new.1340718 (New) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Package is "python-decorator" Tue Dec 1 16:58:08 2026 rev:30 rq:1401127 version:5.3.2 Changes: -------- --- /work/SRC/openSUSE:Factory/python-decorator/python-decorator.changes 2026-06-15 19:41:31.550591763 +0200 +++ /work/SRC/openSUSE:Factory/.python-decorator.new.1340718/python-decorator.changes 2026-12-01 16:58:39.337317229 +0100 @@ -1,0 +2,22 @@ +Fri Nov 27 13:06:38 UTC 2026 - Andrea Manzini <[email protected]> + +- update to 5.3.2: + * Added official support for Python 3.15. + * Support deferred annotations in Python 3.14+ (FunctionMaker + copies annotations without evaluating them). + * FunctionMaker now preserves positional-only parameters. + * Reimplemented getfullargspec on inspect.signature without + following __wrapped__. + * Preserved each layer of __wrapped__ when stacking decorators + or wrapping an already decorated caller. + * Generator functions decorated with a generator caller now + return the value returned by the caller. + * Fixed FunctionMaker.create raising a SyntaxError when + signature contains a return annotation. + * Fixed dispatch_on error handling when called with an + unregistered object() instance or for virtual ancestors of + types that cannot be subclassed. + * Decorating functools.partial no longer alters the original + partial. + +------------------------------------------------------------------- Old: ---- decorator-5.3.1.tar.gz New: ---- decorator-5.3.2.tar.gz ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Other differences: ------------------ ++++++ python-decorator.spec ++++++ --- /var/tmp/diff_new_pack.gPj4S0/_old 2026-12-01 16:58:39.957343141 +0100 +++ /var/tmp/diff_new_pack.gPj4S0/_new 2026-12-01 16:58:39.959343224 +0100 @@ -20,11 +20,10 @@ # %{?sle15_python_module_pythons} Name: python-decorator -Version: 5.3.1 +Version: 5.3.2 Release: 0 Summary: Decorators for Humans License: BSD-2-Clause -Group: Development/Languages/Python URL: https://github.com/micheles/decorator Source: https://files.pythonhosted.org/packages/source/d/decorator/decorator-%{version}.tar.gz BuildRequires: %{python_module pip} ++++++ decorator-5.3.1.tar.gz -> decorator-5.3.2.tar.gz ++++++ diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/decorator-5.3.1/CHANGES.md new/decorator-5.3.2/CHANGES.md --- old/decorator-5.3.1/CHANGES.md 2026-05-18 05:48:18.000000000 +0200 +++ new/decorator-5.3.2/CHANGES.md 2026-11-21 06:11:10.000000000 +0100 @@ -1,7 +1,57 @@ HISTORY -------- -## Unreleased +## 5.3.2 (2026-11-21) + +Added official support for Python 3.15. + +Preserved each layer of `__wrapped__` when stacking decorators or wrapping +an already decorated caller (contributed by Jake Wang). + +Fixed `FunctionMaker.create` raising a `SyntaxError` when the signature +string contains a return annotation, e.g. +`create("f(a) -> int", "return a")` (contributed by Apoorv Darshan). + +Generator functions decorated with a generator caller now return the +value returned by the caller, instead of always returning `None` +(contributed by Huanyi Xie). + +Fixed `dispatch_on` raising `StopIteration` when called with an +unregistered `object()` instance: now the default implementation is +called (contributed by Muneeb Sheikh). + +Corrected the return types of `getfullargspec` and `inspect_sig` in the +stub file (contributed by Huanyi Xie). + +Added homepage and repository links to the package metadata (contributed +by the GitHub user Sinkleberg). + +Fixed `dispatch_on` raising a `TypeError` when an implementation is +registered for a virtual ancestor of a type that cannot be subclassed, +like `range`, `memoryview` or `bool`, or of an enum (reported by +Rajatendu Dey). Also fixed `dispatch_on` raising a `TypeError` when a +class is passed as a dispatch argument. + +Decorating a `functools.partial` no longer alters the original partial +(adding `__wrapped__` and changing its signature), so decorating the same +partial twice no longer rejects valid calls (contributed by Gabriel +Demetrios Lafis). + +`FunctionMaker` now preserves positional-only parameters, so functions +decorated with `decoratorx` or generated by `dispatch_on` reject +positional-only arguments passed by name, and accept keyword arguments +with the same name in `**kwargs` (contributed by Gabriel Demetrios Lafis). + +`getfullargspec`, now reimplemented on top of `inspect.signature`, does not +follow `__wrapped__`, like `inspect.getfullargspec`, so `decoratorx` and +`dispatch_on` keep working with functions decorated by `functools.wraps` +(contributed by Tejesh Vaish). + +In Python 3.14+ `FunctionMaker` copies the deferred annotations of the +original function without evaluating them, so `decoratorx` and +`dispatch_on` work with annotations referring to names imported only +under `TYPE_CHECKING` (issue #177, reported by the GitHub user +bersbersbers and fixed by Mayank Dhingra). ## 5.3.1 (2026-05-18) @@ -12,7 +62,9 @@ Added official support for Python 3.14 (thanks to Hugo van Kemenade, David Cain and the GitHub user bersbersbers). + Fixed a bug with "return await" contributed by Kadir Can Ozden. + Moved decorator.py to a package structure (`decorator/__init__.py`) and added a stub file (`decorator/__init__.pyi`) contributed by Marco Gorelli. diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/decorator-5.3.1/MANIFEST.in new/decorator-5.3.2/MANIFEST.in --- old/decorator-5.3.1/MANIFEST.in 2026-05-17 07:17:05.000000000 +0200 +++ new/decorator-5.3.2/MANIFEST.in 2026-11-21 06:11:10.000000000 +0100 @@ -1,4 +1,4 @@ include CHANGES.md performance.sh -include src/decorator +include src/decorator/*.py src/decorator/*.pyi src/decorator/py.typed include tests/*.py graft docs diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/decorator-5.3.1/PKG-INFO new/decorator-5.3.2/PKG-INFO --- old/decorator-5.3.1/PKG-INFO 2026-05-18 08:03:24.499494600 +0200 +++ new/decorator-5.3.2/PKG-INFO 2026-11-21 06:12:27.517733300 +0100 @@ -1,9 +1,11 @@ Metadata-Version: 2.4 Name: decorator -Version: 5.3.1 +Version: 5.3.2 Summary: Decorators for Humans Author-email: Michele Simionato <[email protected]> License: BSD-2-Clause +Project-URL: Homepage, https://github.com/micheles/decorator +Project-URL: Repository, https://github.com/micheles/decorator Keywords: decorators Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers @@ -17,6 +19,7 @@ Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Topic :: Software Development :: Libraries Classifier: Topic :: Utilities diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/decorator-5.3.1/docs/documentation.md new/decorator-5.3.2/docs/documentation.md --- old/decorator-5.3.1/docs/documentation.md 2026-05-18 08:02:23.000000000 +0200 +++ new/decorator-5.3.2/docs/documentation.md 2026-11-21 06:11:10.000000000 +0100 @@ -3,9 +3,9 @@ |Author | Michele Simionato| |---|---| |E-mail | [email protected]| -|Version| 5.3.1 (2026-05-18)| -|Supports| Python 3.8, 3.9, 3.10, 3.11, 3.12, 3.13, 3.14| -|Download page| https://pypi.org/project/decorator/5.3.1| +|Version| 5.3.2 (2026-11-21)| +|Supports| Python 3.8, 3.9, 3.10, 3.11, 3.12, 3.13, 3.14, 3.15| +|Download page| https://pypi.org/project/decorator/5.3.2| |Installation| ``pip install decorator``| |License | BSD license| diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/decorator-5.3.1/pyproject.toml new/decorator-5.3.2/pyproject.toml --- old/decorator-5.3.1/pyproject.toml 2026-05-18 05:55:29.000000000 +0200 +++ new/decorator-5.3.2/pyproject.toml 2026-11-21 06:11:10.000000000 +0100 @@ -1,5 +1,5 @@ [build-system] -requires = ["setuptools>=77.0.0"] +requires = ["setuptools>=75.3.4"] build-backend = "setuptools.build_meta" [project] @@ -26,10 +26,15 @@ 'Programming Language :: Python :: 3.12', 'Programming Language :: Python :: 3.13', 'Programming Language :: Python :: 3.14', + 'Programming Language :: Python :: 3.15', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities'] +[project.urls] +Homepage = "https://github.com/micheles/decorator" +Repository = "https://github.com/micheles/decorator" + [tool.setuptools.dynamic] version.attr = "decorator.__version__" diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/decorator-5.3.1/src/decorator/__init__.py new/decorator-5.3.2/src/decorator/__init__.py --- old/decorator-5.3.1/src/decorator/__init__.py 2026-05-18 08:01:07.000000000 +0200 +++ new/decorator-5.3.2/src/decorator/__init__.py 2026-11-21 06:11:10.000000000 +0100 @@ -38,24 +38,94 @@ import operator import itertools import functools +import copy from contextlib import _GeneratorContextManager -from inspect import getfullargspec, iscoroutinefunction, isgeneratorfunction -from typing import Any, Dict, List, Optional +from collections import namedtuple +from inspect import Parameter, iscoroutinefunction, isgeneratorfunction +from typing import Any, Callable, Dict, List, Optional try: import annotationlib # in Python 3.14+ - def inspect_sig(func): + def inspect_sig(func, *, follow_wrapped=True): return inspect.signature( - func, annotation_format=annotationlib.Format.FORWARDREF) + func, follow_wrapped=follow_wrapped, + annotation_format=annotationlib.Format.FORWARDREF) except ImportError: inspect_sig = inspect.signature -__version__ = '5.3.1' +__version__ = '5.3.2' DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(') POS = inspect.Parameter.POSITIONAL_OR_KEYWORD EMPTY = inspect.Parameter.empty +FullArgSpec = namedtuple('FullArgSpec', [ + 'args', 'varargs', 'varkw', 'defaults', + 'kwonlyargs', 'kwonlydefaults', 'annotations' +]) + + +def getfullargspec(func): + """ + A pure re-implementation of inspect.getfullargspec(func) + built entirely on top of the modern inspect.signature API. + This is needed to work around a python 3.14 forward references bug. + """ + # like inspect.getfullargspec, do not follow the __wrapped__ chain + return _fullargspec(inspect_sig(func, follow_wrapped=False)) + + +def _fullargspec(sig): + """ + Convert an inspect.Signature object into a FullArgSpec + """ + args = [] + varargs = None + varkw = None + defaults_list = [] + kwonlyargs = [] + kwonlydefaults = {} + annotations = {} + + # Process return annotation if it exists + if sig.return_annotation is not inspect.Signature.empty: + annotations['return'] = sig.return_annotation + + for name, param in sig.parameters.items(): + # Collect annotations for any parameter that defines one + if param.annotation is not Parameter.empty: + annotations[name] = param.annotation + + # Segment parameters by their operational "kind" + if param.kind in (Parameter.POSITIONAL_ONLY, + Parameter.POSITIONAL_OR_KEYWORD): + args.append(name) + # Track defaults for standard positional arguments + if param.default is not Parameter.empty: + defaults_list.append(param.default) + else: + # Legacy behavior quirk: if a non-default argument follows a + # defaulted positional-only argument, the previous defaults + # are wiped + defaults_list.clear() + + elif param.kind == Parameter.VAR_POSITIONAL: + varargs = name + + elif param.kind == Parameter.KEYWORD_ONLY: + kwonlyargs.append(name) + if param.default is not Parameter.empty: + kwonlydefaults[name] = param.default + + elif param.kind == Parameter.VAR_KEYWORD: + varkw = name + + # Format output fields to match precise spec specifications + defaults = tuple(defaults_list) if defaults_list else None + kwonlydefaults = kwonlydefaults if kwonlydefaults else None + + return FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, + kwonlydefaults, annotations) # this is not used anymore in the core, but kept for backward compatibility @@ -86,8 +156,13 @@ self.doc = func.__doc__ self.module = func.__module__ if inspect.isroutine(func) or isinstance(func, functools.partial): - argspec = getfullargspec(func) - self.annotations = getattr(func, '__annotations__', {}) + sig = inspect_sig(func, follow_wrapped=False) + argspec = _fullargspec(sig) + # in Python 3.14+ copy the deferred annotations without + # evaluating them, since they can refer to undefined names + self._annotate = getattr(func, '__annotate__', None) + if self._annotate is None: + self.annotations = getattr(func, '__annotations__', {}) for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs', 'kwonlydefaults'): setattr(self, a, getattr(argspec, a)) @@ -95,6 +170,11 @@ setattr(self, 'arg%d' % i, arg) allargs = list(self.args) allshortargs = list(self.args) + posonly_count = sum( + p.kind == Parameter.POSITIONAL_ONLY + for p in sig.parameters.values()) + if posonly_count: + allargs.insert(posonly_count, '/') if self.varargs: allargs.append('*' + self.varargs) allshortargs.append('*' + self.varargs) @@ -137,6 +217,8 @@ func.__defaults__ = self.defaults func.__kwdefaults__ = self.kwonlydefaults or None func.__annotations__ = getattr(self, 'annotations', None) + if getattr(self, '_annotate', None) is not None: + func.__annotate__ = self._annotate try: frame = sys._getframe(3) except AttributeError: # for IronPython and similar implementations @@ -191,22 +273,28 @@ attribute __source__ is added to the result. The attributes attrs are added, if any. """ - if isinstance(obj, str): # "name(signature)" + if isinstance(obj, str): # "name(signature)" or "name(signature) -> ret" name, rest = obj.strip().split('(', 1) - signature = rest[:-1] # strip a right parens + # split the argument list from an optional return annotation; + # the argument list ends at the last right parens + signature, _, return_annotation = rest.rpartition(')') func = None else: # a function name = None signature = None + return_annotation = '' func = obj self = cls(func, name, signature, defaults, doc, module) + self.return_annotation = return_annotation # e.g. " -> int" ibody = '\n'.join(' ' + line for line in body.splitlines()) caller = evaldict.get('_call_') # when called from `decorate` if caller and iscoroutinefunction(caller): - body = ('async def %(name)s(%(signature)s):\n' + ibody) + body = ('async def %(name)s(%(signature)s)' + '%(return_annotation)s:\n' + ibody) body = re.sub(r'\breturn\b', 'return await', body) else: - body = 'def %(name)s(%(signature)s):\n' + ibody + body = ('def %(name)s(%(signature)s)' + '%(return_annotation)s:\n' + ibody) return self.make(body, evaldict, addsource, **attrs) @@ -229,25 +317,30 @@ """ sig = inspect_sig(func) if isinstance(func, functools.partial): + func = copy.copy(func) + func.__dict__ = func.__dict__.copy() func = functools.update_wrapper(func, func.func) + fun: Callable[..., Any] if iscoroutinefunction(caller): - async def fun(*args, **kw): + async def async_fun(*args, **kw): if not kwsyntax: args, kw = fix(args, kw, sig) return await caller(func, *(extras + args), **kw) + fun = async_fun elif isgeneratorfunction(caller): - def fun(*args, **kw): + def generator_fun(*args, **kw): if not kwsyntax: args, kw = fix(args, kw, sig) - yield from caller(func, *(extras + args), **kw) + return (yield from caller(func, *(extras + args), **kw)) + fun = generator_fun else: - def fun(*args, **kw): + def sync_fun(*args, **kw): if not kwsyntax: args, kw = fix(args, kw, sig) return caller(func, *(extras + args), **kw) + fun = sync_fun fun.__doc__ = func.__doc__ - fun.__wrapped__ = func fun.__signature__ = sig fun.__qualname__ = func.__qualname__ # builtin functions like defaultdict.__setitem__ lack many attributes @@ -261,7 +354,7 @@ pass try: fun.__annotations__ = func.__annotations__ - except AttributeError: + except (AttributeError, NameError): pass try: fun.__module__ = func.__module__ @@ -275,6 +368,7 @@ fun.__dict__.update(func.__dict__) except AttributeError: pass + fun.__wrapped__ = func return fun @@ -316,10 +410,10 @@ dec.__signature__ = sig.replace(parameters=dec_params) dec.__name__ = caller.__name__ dec.__doc__ = caller.__doc__ - dec.__wrapped__ = caller dec.__qualname__ = caller.__qualname__ dec.__kwdefaults__ = getattr(caller, '__kwdefaults__', None) dec.__dict__.update(caller.__dict__) + dec.__wrapped__ = caller return dec @@ -364,6 +458,34 @@ vancestors.append(a) +def _virtual_mro(t, va): + """ + Return the MRO that a class with bases ``(t, va)`` would have, without + the class itself. The C3 linearization is computed directly, since + creating such a class is impossible when ``t`` is final (like ``range``, + ``memoryview`` or ``bool``) or its metaclass conflicts with the one + of ``va`` (like for enums), and it would have side effects if ``t`` + defines ``__init_subclass__``. + """ + seqs = [list(t.__mro__), list(va.__mro__), [t, va]] + mro = [] + while True: + seqs = [seq for seq in seqs if seq] + if not seqs: + return mro + for seq in seqs: # look for a head not in the tail of any sequence + head = seq[0] + if not any(head in s[1:] for s in seqs): + break + else: + raise RuntimeError('Inconsistent MRO for {} with virtual ' + 'ancestor {}'.format(t, va)) + mro.append(head) + for seq in seqs: + if seq[0] is head: + del seq[0] + + # inspired from simplegeneric by P.J. Eby and functools.singledispatch def dispatch_on(*dispatch_args): """ @@ -397,7 +519,7 @@ ras = [[] for _ in range(len(dispatch_args))] for types_ in typemap: for t, type_, ra in zip(types, types_, ras): - if issubclass(t, type_) and type_ not in t.mro(): + if issubclass(t, type_) and type_ not in t.__mro__: append(type_, ra) return [set(ra) for ra in ras] @@ -414,10 +536,11 @@ 'Ambiguous dispatch for {}: {}'.format(t, vas)) elif n_vas == 1: va, = vas - mro = type('t', (t, va), {}).mro()[1:] + mro = _virtual_mro(t, va) else: - mro = t.mro() - lists.append(mro[:-1]) # discard t and object + # not t.mro(), which is unbound when t is a metaclass + mro = list(t.__mro__) + lists.append(mro[:-1]) # discard object return lists def register(*types): @@ -451,7 +574,7 @@ else: return f(*args, **kw) combinations = itertools.product(*ancestors(*types)) - next(combinations) # the first one has been already tried + next(combinations, None) # the first one has been already tried for types_ in combinations: f = typemap.get(types_) if f is not None: diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/decorator-5.3.1/src/decorator/__init__.pyi new/decorator-5.3.2/src/decorator/__init__.pyi --- old/decorator-5.3.1/src/decorator/__init__.pyi 2026-05-17 08:21:49.000000000 +0200 +++ new/decorator-5.3.2/src/decorator/__init__.pyi 2026-11-21 04:33:22.000000000 +0100 @@ -1,11 +1,11 @@ import inspect -import annotationlib +import sys from builtins import dict as _dict # alias to avoid conflicts with attribute name from collections.abc import Callable, Generator, Iterator from contextlib import _GeneratorContextManager -from inspect import Signature, getfullargspec as getfullargspec, iscoroutinefunction as iscoroutinefunction +from inspect import Signature, iscoroutinefunction, isgeneratorfunction from re import Pattern -from typing import Any, Final, Literal, TypeVar, Tuple +from typing import Any, Final, Literal, NamedTuple, TypeVar from typing_extensions import ParamSpec _C = TypeVar("_C", bound=Callable[..., Any]) @@ -17,9 +17,26 @@ POS: Final[Literal[inspect._ParameterKind.POSITIONAL_OR_KEYWORD]] EMPTY: Final[type[inspect._empty]] -def inspect_sig( +class FullArgSpec(NamedTuple): + args: list[str] + varargs: str | None + varkw: str | None + defaults: tuple[Any, ...] | None + kwonlyargs: list[str] + kwonlydefaults: _dict[str, Any] | None + annotations: _dict[str, Any] + +if sys.version_info >= (3, 14): + def inspect_sig(func: _Func, *, follow_wrapped: bool = True) -> Signature: ... +else: + from inspect import signature as _signature + + inspect_sig = _signature + + +def getfullargspec( func: _Func -) -> Tuple: ... +) -> FullArgSpec: ... class FunctionMaker: diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/decorator-5.3.1/src/decorator.egg-info/PKG-INFO new/decorator-5.3.2/src/decorator.egg-info/PKG-INFO --- old/decorator-5.3.1/src/decorator.egg-info/PKG-INFO 2026-05-18 08:03:24.000000000 +0200 +++ new/decorator-5.3.2/src/decorator.egg-info/PKG-INFO 2026-11-21 06:12:27.000000000 +0100 @@ -1,9 +1,11 @@ Metadata-Version: 2.4 Name: decorator -Version: 5.3.1 +Version: 5.3.2 Summary: Decorators for Humans Author-email: Michele Simionato <[email protected]> License: BSD-2-Clause +Project-URL: Homepage, https://github.com/micheles/decorator +Project-URL: Repository, https://github.com/micheles/decorator Keywords: decorators Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers @@ -17,6 +19,7 @@ Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Topic :: Software Development :: Libraries Classifier: Topic :: Utilities diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/decorator-5.3.1/tests/documentation.py new/decorator-5.3.2/tests/documentation.py --- old/decorator-5.3.1/tests/documentation.py 2026-05-17 09:11:32.000000000 +0200 +++ new/decorator-5.3.2/tests/documentation.py 2026-11-21 06:11:10.000000000 +0100 @@ -14,7 +14,7 @@ |---|---| |E-mail | [email protected]| |Version| $VERSION ($DATE)| -|Supports| Python 3.8, 3.9, 3.10, 3.11, 3.12, 3.13, 3.14| +|Supports| Python 3.8, 3.9, 3.10, 3.11, 3.12, 3.13, 3.14, 3.15| |Download page| https://pypi.org/project/decorator/$VERSION| |Installation| ``pip install decorator``| |License | BSD license| diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/decorator-5.3.1/tests/test.py new/decorator-5.3.2/tests/test.py --- old/decorator-5.3.1/tests/test.py 2026-05-17 08:21:49.000000000 +0200 +++ new/decorator-5.3.2/tests/test.py 2026-11-21 06:11:08.000000000 +0100 @@ -1,19 +1,21 @@ import sys import doctest import unittest +import enum import decimal import inspect import functools import asyncio from collections import defaultdict, ChainMap, abc as c -from decorator import dispatch_on, contextmanager, decorator +from decorator import (dispatch_on, contextmanager, decorator, decoratorx, + FunctionMaker, getfullargspec) try: from . import documentation as doc # good with pytest except ImportError: import documentation as doc # good with `python src/tests/test.py` from typing import TYPE_CHECKING # introduced in 3.5 if TYPE_CHECKING: # only inside mypy - from datetime import date + from collections.abc import Sequence PYVER = sys.version_info[:2] @@ -71,6 +73,22 @@ self.assertTrue(inspect.isgeneratorfunction(new)) self.assertEqual(list(new()), [1, 4, 9]) + def test_generator_return_value(self): + @decorator + def identity(func, *args, **kw): + return (yield from func(*args, **kw)) + + @identity + def numbers(): + yield 1 + return 42 + + gen = numbers() + self.assertEqual(next(gen), 1) + with self.assertRaises(StopIteration) as caught: + next(gen) + self.assertEqual(caught.exception.value, 42) + class DocumentationTestCase(unittest.TestCase): def test(self): @@ -107,6 +125,34 @@ class ExtraTestCase(unittest.TestCase): + def test_stacked_wrapped(self): + @decorator + def increment(func, *args, **kwargs): + return func(*args, **kwargs) + 1 + + def original(value): + return value + + first = increment(original) + second = increment(first) + self.assertEqual(second(3), 5) + self.assertIs(second.__wrapped__, first) + self.assertEqual(second.__wrapped__(3), 4) + self.assertIs(inspect.unwrap(second, stop=lambda f: f is first), first) + self.assertIs(inspect.unwrap(second), original) + + def test_wrapped_caller(self): + def caller(func, *args, **kwargs): + return func(*args, **kwargs) + + @functools.wraps(caller) + def wrapped_caller(*args, **kwargs): + return caller(*args, **kwargs) + + dec = decorator(wrapped_caller) + self.assertIs(dec.__wrapped__, wrapped_caller) + self.assertIs(dec.__wrapped__.__wrapped__, caller) + def test_qualname(self): self.assertEqual(doc.operation1.__qualname__, 'operation1') @@ -114,6 +160,84 @@ sig = inspect.signature(doc.f1) self.assertEqual(str(sig), '(x)') + def test_return_annotation(self): + # see https://github.com/micheles/decorator/issues/138 + def add(a, b): + return a + b + + # a signature string without a return annotation still works + add2 = FunctionMaker.create( + 'add2(a: int, b: int)', 'return add(a, b)', + evaldict={'add': add}) + self.assertEqual(add2(6, 8), 14) + + # a signature string with a return annotation must not raise + add3 = FunctionMaker.create( + 'add3(a: int, b: int) -> int', 'return add(a, b)', + evaldict={'add': add}) + self.assertEqual(add3(6, 8), 14) + + def test_decoratorx_positional_only_parameters(self): + @decoratorx + def identity(func, *args, **kwargs): + return func(*args, **kwargs) + + @identity + def target(a, /, b=2, *, c=3): + return a + b + c + + self.assertEqual(target.__code__.co_posonlyargcount, 1) + self.assertEqual(target(1), 6) + self.assertEqual(target(1, b=4, c=5), 10) + with self.assertRaises(TypeError): + target(a=1) + + @identity + def kwtarget(a, /, **kw): + return a, kw + + # a positional-only name can also be passed in **kw + self.assertEqual(kwtarget(1, a=2), (1, {'a': 2})) + + def test_getfullargspec_does_not_follow_wrapped(self): + # see https://github.com/micheles/decorator/pull/197 + def original(hidden): + return hidden + + @functools.wraps(original) + def wrapper(actual, optional=3, *items, flag=True, **options): + return actual, optional, items, flag, options + + self.assertEqual(getfullargspec(wrapper), + inspect.getfullargspec(wrapper)) + wrapper.__wrapped__ = wrapper # a cycle is not a problem + self.assertEqual(getfullargspec(wrapper), + inspect.getfullargspec(wrapper)) + + def test_wrapped_functions_keep_their_signature(self): + def original(hidden): + return hidden + + @functools.wraps(original) + def wrapper(actual, optional=3): + return actual + optional + + @decoratorx + def double(func, *args, **kw): + return func(*args, **kw) * 2 + + self.assertEqual(double(wrapper)(actual=2), 10) + self.assertEqual(double(wrapper)(2, 5), 14) + + generic = dispatch_on('actual')(wrapper) + + @generic.register(str) + def generic_str(actual, optional=3): + return actual * optional + + self.assertEqual(generic(1), 4) + self.assertEqual(generic('x'), 'xxx') + def test_unique_filenames(self): @decorator def d1(f, *args, **kwargs): @@ -205,6 +329,109 @@ class TestSingleDispatch(unittest.TestCase): + def test_object_uses_default(self): + @singledispatch + def g(obj): + return "base" + + self.assertEqual(g(object()), "base") + + @g.register(object) + def g_object(obj): + return "object" + + self.assertEqual(g(object()), "object") + + def test_object_uses_default_in_multiple_dispatch(self): + @dispatch_on('left', 'right') + def g(left, right): + return "base" + + self.assertEqual(g(object(), 1), "base") + self.assertEqual(g(1, object()), "base") + self.assertEqual(g(object(), object()), "base") + + def test_virtual_ancestor_of_final_types(self): + # see https://github.com/micheles/decorator/issues/198 + @singledispatch + def g(obj): + return "base" + + @g.register(c.Sequence) + def g_sequence(obj): + return "sequence" + + self.assertEqual(g([1, 2]), "sequence") + self.assertEqual(g(range(3)), "sequence") + self.assertEqual(g(memoryview(b"abc")), "sequence") + self.assertEqual(g.dispatch_info(range)[:2], + [('range',), ('Sequence',)]) + + class Color(enum.Enum): # final, with a metaclass other than ABCMeta + RED = 1 + + @singledispatch + def h(obj): + return "base" + + @h.register(c.Hashable) + def h_hashable(obj): + return "hashable" + + for obj in (True, None, Ellipsis, NotImplemented, Color.RED): + self.assertEqual(h(obj), "hashable") + + def test_virtual_ancestor_of_final_types_in_multiple_dispatch(self): + @dispatch_on('left', 'right') + def g(left, right): + return "base" + + @g.register(c.Sequence, c.Sequence) + def g_sequences(left, right): + return "sequences" + + for left in (range(2), memoryview(b"ab")): + for right in (range(2), memoryview(b"ab")): + self.assertEqual(g(left, right), "sequences") + self.assertEqual(g(range(2), 1), "base") + + def test_virtual_ancestor_without_subclassing(self): + # computing the virtual MRO must not create subclasses of the type + subclasses = [] + + class Base(object): + def __init_subclass__(cls, **kw): + super().__init_subclass__(**kw) + subclasses.append(cls) + + def __len__(self): # implicitly a Sized + return 0 + + @singledispatch + def g(obj): + return "base" + + @g.register(c.Sized) + def g_sized(obj): + return "sized" + + self.assertEqual(g(Base()), "sized") + self.assertEqual(subclasses, []) + + def test_class_arguments(self): + # type(int) is type, and type.mro() is an unbound method + @singledispatch + def g(obj): + return "base" + + @g.register(c.Sized) + def g_sized(obj): + return "sized" + + self.assertEqual(g(int), "base") + self.assertEqual(g(list), "base") # the class is not Sized + self.assertEqual(g(c.Sized), "base") # type is ABCMeta + def test_simple_overloads(self): @singledispatch def g(obj): @@ -528,11 +755,147 @@ out = partial_func("y") self.assertEqual(out, '<before>xy<after>') + def test_decorating_partial_does_not_change_its_signature(self): + def origin_func(x, y): + return x + y + original = functools.partial(origin_func, "x") + original.custom = "preserved" + signature = inspect.signature(original) + + first = partial_before_after(original) + self.assertEqual(inspect.signature(original), signature) + self.assertFalse(hasattr(original, '__wrapped__')) + self.assertEqual(first.custom, "preserved") + + second = partial_before_after(original) + self.assertEqual(inspect.signature(first), signature) + self.assertEqual(inspect.signature(second), signature) + self.assertEqual(first("y"), '<before>xy<after>') + self.assertEqual(second("z"), '<before>xz<after>') + + +class FunctionMakerAnnotationsTestCase(unittest.TestCase): + @staticmethod + def identity(func, *args, **kwargs): + return func(*args, **kwargs) + + def test_concrete_annotations_are_preserved(self): + def original(value: int) -> str: + return str(value) + + wrapped = decoratorx(self.identity)(original) + self.assertEqual(wrapped(3), '3') + self.assertEqual(wrapped.__annotations__, original.__annotations__) + + def test_string_annotations_are_preserved(self): + namespace = {} + exec('from __future__ import annotations\n' + 'def original(value: Undefined) -> Undefined: return value', namespace) + original = namespace['original'] + wrapped = decoratorx(self.identity)(original) + self.assertEqual(wrapped(3), 3) + self.assertEqual(wrapped.__annotations__, original.__annotations__) + self.assertEqual(wrapped.__annotations__, + {'value': 'Undefined', 'return': 'Undefined'}) + + @unittest.skipIf(PYVER < (3, 14), 'requires deferred annotations') + def test_failing_annotations_are_not_lost(self): + import annotationlib + + namespace = {} + exec('import types\n' + 'def original(value: types.NotThere) -> int: return value', namespace) + wrapped = decoratorx(self.identity)(namespace['original']) + self.assertEqual(wrapped(3), 3) + self.assertEqual(annotationlib.get_annotations( + wrapped, format=annotationlib.Format.STRING), + {'value': 'types.NotThere', 'return': 'int'}) + + @unittest.skipIf(PYVER < (3, 14), 'requires deferred annotations') + def test_type_checking_only_annotations_do_not_prevent_decoration(self): + import annotationlib + + namespace = {} + exec('from typing import TYPE_CHECKING\n' + 'if TYPE_CHECKING:\n' + ' from collections.abc import Sequence\n' + 'def original(values: Sequence[int], *, factor: int = 2) -> int:\n' + ' return len(values) * factor', namespace) + original = namespace['original'] + wrapped = decoratorx(self.identity)(original) + self.assertEqual(wrapped([1, 2], factor=3), 6) + self.assertEqual(wrapped.__code__.co_argcount, 1) + self.assertEqual(wrapped.__code__.co_kwonlyargcount, 1) + self.assertEqual(wrapped.__kwdefaults__, {'factor': 2}) + annotations = annotationlib.get_annotations( + wrapped, format=annotationlib.Format.FORWARDREF) + self.assertIsInstance(annotations['values'], annotationlib.ForwardRef) + original_annotations = annotationlib.get_annotations( + original, format=annotationlib.Format.FORWARDREF) + self.assertEqual(annotations['values'].__forward_arg__, + original_annotations['values'].__forward_arg__) + namespace['Sequence'] = c.Sequence + self.assertEqual(wrapped.__annotations__['values'], c.Sequence[int]) + self.assertIs(annotations['return'], int) + + @unittest.skipIf(PYVER < (3, 14), 'requires deferred annotations') + def test_annotations_resolve_after_a_later_definition(self): + namespace = {} + exec('def original(value: Later) -> Later: return value', namespace) + original = namespace['original'] + wrapped = decoratorx(self.identity)(original) + second = decoratorx(self.identity)(wrapped) + self.assertEqual(second(3), 3) + with self.assertRaises(NameError): + second.__annotations__ + namespace['Later'] = int + expected = {'value': int, 'return': int} + self.assertEqual(second.__annotations__, expected) + self.assertEqual(wrapped.__annotations__, expected) + self.assertEqual(original.__annotations__, expected) + + @unittest.skipIf(PYVER < (3, 14), 'requires deferred annotations') + def test_annotations_keep_the_original_closure(self): + namespace = {} + exec('def factory():\n' + ' class Local: pass\n' + ' def original(value: Local, other: Later) -> Local:\n' + ' return value\n' + ' return original, Local\n' + 'original, Local = factory()', namespace) + original = namespace['original'] + generated = FunctionMaker.create( + original, 'return target(value, other)', {'target': original}) + namespace['Later'] = str + local = namespace['Local'] + value = local() + self.assertIs(generated(value, 'text'), value) + self.assertEqual(generated.__annotations__, + {'value': local, 'other': str, 'return': local}) + + @unittest.skipIf(PYVER < (3, 14), 'requires deferred annotations') + def test_async_wrapper_keeps_deferred_annotations(self): + async def caller(func, *args, **kwargs): + return await func(*args, **kwargs) + + namespace = {} + exec('async def original(value: Later) -> Later: return value', namespace) + wrapped = decoratorx(caller)(namespace['original']) + self.assertTrue(inspect.iscoroutinefunction(wrapped)) + self.assertEqual(asyncio.run(wrapped(3)), 3) + namespace['Later'] = int + self.assertEqual(wrapped.__annotations__, {'value': int, 'return': int}) + if PYVER >= (3, 14): - # testing forward references in python 3.14+ + # testing forward references in python 3.14+, see + # https://github.com/micheles/decorator/issues/177#issuecomment-4471451108 @decorator - def get_dob() -> date: + def identity(func, *args, **kwargs): + return func(*args, **kwargs) + + @identity + def foo(ints: Sequence[int]) -> None: pass
