Support positional-only parameters in classmethods (#11635)

This commit is contained in:
Adam Turner 2023-08-23 19:33:16 +01:00 committed by GitHub
parent 02cb02ccfb
commit a73fb59a71
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 49 additions and 41 deletions

View File

@ -5,6 +5,8 @@ Dependencies
------------
* #11576: Require sphinxcontrib-serializinghtml 1.1.9.
* #11543: autodoc: Support positional-only parameters in ``classmethod`` methods
when ``autodoc_preserve_defaults`` is ``True``.
Bugs fixed
----------

View File

@ -135,13 +135,21 @@ def update_defvalue(app: Sphinx, obj: Any, bound_method: bool) -> None:
try:
args = _get_arguments(obj)
except SyntaxError:
return
if args is None:
# If the object is a built-in, we won't be always able to recover
# the function definition and its arguments. This happens if *obj*
# is the `__init__` method generated automatically for dataclasses.
return
if args.defaults or args.kw_defaults:
if not args.defaults and not args.kw_defaults:
return
try:
if bound_method and inspect.ismethod(obj) and hasattr(obj, '__func__'):
sig = inspect.signature(obj.__func__)
else:
sig = inspect.signature(obj)
defaults = list(args.defaults)
kw_defaults = list(args.kw_defaults)
@ -165,21 +173,19 @@ def update_defvalue(app: Sphinx, obj: Any, bound_method: bool) -> None:
value = ast_unparse(default)
parameters[i] = param.replace(default=DefaultValue(value))
if bound_method and inspect.ismethod(obj):
# classmethods
cls = inspect.Parameter('cls', inspect.Parameter.POSITIONAL_OR_KEYWORD)
parameters.insert(0, cls)
sig = sig.replace(parameters=parameters)
if bound_method and inspect.ismethod(obj):
# classmethods can't be assigned __signature__ attribute.
obj.__dict__['__signature__'] = sig
else:
try:
obj.__signature__ = sig
except AttributeError:
# __signature__ can't be set directly on bound methods.
obj.__dict__['__signature__'] = sig
except (AttributeError, TypeError):
# failed to update signature (ex. built-in or extension types)
pass
except NotImplementedError as exc: # failed to ast.unparse()
# Failed to update signature (e.g. built-in or extension types).
# For user-defined functions, "obj" may not have __dict__,
# e.g. when decorated with a class that defines __slots__.
# In this case, we can't set __signature__.
return
except NotImplementedError as exc: # failed to ast_unparse()
logger.warning(__("Failed to parse a default argument value for %r: %s"), obj, exc)