Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 34k
gh-101552: Allow pydoc to display signatures in source format#124669
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
13 commits Select commit Hold shift + click to select a range
f806791 gh-101552: Add format argument to inspect.signature
JelleZijlstra 4e319cf Merge remote-tracking branch 'upstream/main'
JelleZijlstra 38c4b42 fixes
JelleZijlstra c33c4cc Merge remote-tracking branch 'upstream/main' into sigdocs
JelleZijlstra 9c7b972 missing file
JelleZijlstra b14a719 blurb
JelleZijlstra 33ef93d format -> annotation_format
JelleZijlstra afdf4fc Apply suggestions from code review
JelleZijlstra 1549080 Update Lib/inspect.py
JelleZijlstra 5831cc4 Merge remote-tracking branch 'upstream/main' into sigdocs
JelleZijlstra 35ee105 Renamings
JelleZijlstra c549c70 Update Misc/NEWS.d/next/Library/2024-09-27-06-39-32.gh-issue-101552.x…
JelleZijlstra e448b82 Merge branch 'main' into sigdocs
JelleZijlstra File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -140,6 +140,7 @@ | ||
| import abc | ||
| from annotationlib import Format | ||
| from annotationlib import get_annotations # re-exported | ||
| import ast | ||
| import dis | ||
| @@ -1319,7 +1320,9 @@ def getargvalues(frame): | ||
| args, varargs, varkw = getargs(frame.f_code) | ||
| return ArgInfo(args, varargs, varkw, frame.f_locals) | ||
| def formatannotation(annotation, base_module=None): | ||
| def formatannotation(annotation, base_module=None, *, quote_annotation_strings=True): | ||
| if not quote_annotation_strings and isinstance(annotation, str): | ||
| return annotation | ||
| if getattr(annotation, '__module__', None) == 'typing': | ||
| def repl(match): | ||
| text = match.group() | ||
| @@ -2270,7 +2273,8 @@ def _signature_from_builtin(cls, func, skip_bound_arg=True): | ||
| def _signature_from_function(cls, func, skip_bound_arg=True, | ||
| globals=None, locals=None, eval_str=False): | ||
| globals=None, locals=None, eval_str=False, | ||
| *, annotation_format=Format.VALUE): | ||
| """Private helper: constructs Signature for the given python function.""" | ||
| is_duck_function = False | ||
| @@ -2296,7 +2300,8 @@ def _signature_from_function(cls, func, skip_bound_arg=True, | ||
| positional = arg_names[:pos_count] | ||
| keyword_only_count = func_code.co_kwonlyargcount | ||
| keyword_only = arg_names[pos_count:pos_count + keyword_only_count] | ||
| annotations = get_annotations(func, globals=globals, locals=locals, eval_str=eval_str) | ||
| annotations = get_annotations(func, globals=globals, locals=locals, eval_str=eval_str, | ||
| format=annotation_format) | ||
JelleZijlstra marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading. Please reload this page. | ||
| defaults = func.__defaults__ | ||
| kwdefaults = func.__kwdefaults__ | ||
| @@ -2379,7 +2384,8 @@ def _signature_from_callable(obj, *, | ||
| globals=None, | ||
| locals=None, | ||
| eval_str=False, | ||
| sigcls): | ||
| sigcls, | ||
| annotation_format=Format.VALUE): | ||
| """Private helper function to get signature for arbitrary | ||
| callable objects. | ||
| @@ -2391,7 +2397,8 @@ def _signature_from_callable(obj, *, | ||
| globals=globals, | ||
| locals=locals, | ||
| sigcls=sigcls, | ||
| eval_str=eval_str) | ||
| eval_str=eval_str, | ||
| annotation_format=annotation_format) | ||
| if not callable(obj): | ||
| raise TypeError('{!r} is not a callable object'.format(obj)) | ||
| @@ -2472,7 +2479,8 @@ def _signature_from_callable(obj, *, | ||
| # of a Python function (Cython functions, for instance), then: | ||
| return _signature_from_function(sigcls, obj, | ||
| skip_bound_arg=skip_bound_arg, | ||
| globals=globals, locals=locals, eval_str=eval_str) | ||
| globals=globals, locals=locals, eval_str=eval_str, | ||
| annotation_format=annotation_format) | ||
| if _signature_is_builtin(obj): | ||
| return _signature_from_builtin(sigcls, obj, | ||
| @@ -2707,13 +2715,17 @@ def replace(self, *, name=_void, kind=_void, | ||
| return type(self)(name, kind, default=default, annotation=annotation) | ||
| def __str__(self): | ||
| return self._format() | ||
| def _format(self, *, quote_annotation_strings=True): | ||
| kind = self.kind | ||
| formatted = self._name | ||
| # Add annotation and default value | ||
| if self._annotation is not _empty: | ||
| formatted = '{}:{}'.format(formatted, | ||
| formatannotation(self._annotation)) | ||
| annotation = formatannotation(self._annotation, | ||
| quote_annotation_strings=quote_annotation_strings) | ||
| formatted = '{}:{}'.format(formatted, annotation) | ||
| if self._default is not _empty: | ||
| if self._annotation is not _empty: | ||
| @@ -2961,11 +2973,13 @@ def __init__(self, parameters=None, *, return_annotation=_empty, | ||
| @classmethod | ||
| def from_callable(cls, obj, *, | ||
| follow_wrapped=True, globals=None, locals=None, eval_str=False): | ||
| follow_wrapped=True, globals=None, locals=None, eval_str=False, | ||
| annotation_format=Format.VALUE): | ||
| """Constructs Signature for the given callable object.""" | ||
| return _signature_from_callable(obj, sigcls=cls, | ||
| follow_wrapper_chains=follow_wrapped, | ||
| globals=globals, locals=locals, eval_str=eval_str) | ||
| globals=globals, locals=locals, eval_str=eval_str, | ||
| annotation_format=annotation_format) | ||
| @property | ||
| def parameters(self): | ||
| @@ -3180,19 +3194,24 @@ def __repr__(self): | ||
| def __str__(self): | ||
| return self.format() | ||
| def format(self, *, max_width=None): | ||
| def format(self, *, max_width=None, quote_annotation_strings=True): | ||
| """Create a string representation of the Signature object. | ||
| If *max_width* integer is passed, | ||
| signature will try to fit into the *max_width*. | ||
| If signature is longer than *max_width*, | ||
| all parameters will be on separate lines. | ||
| If *quote_annotation_strings* is False, annotations | ||
| in the signature are displayed without opening and closing quotation | ||
| marks. This is useful when the signature was created with the | ||
| STRING format or when ``from __future__ import annotations`` was used. | ||
| """ | ||
| result = [] | ||
| render_pos_only_separator = False | ||
| render_kw_only_separator = True | ||
| for param in self.parameters.values(): | ||
| formatted = str(param) | ||
| formatted = param._format(quote_annotation_strings=quote_annotation_strings) | ||
| kind = param.kind | ||
| @@ -3229,16 +3248,19 @@ def format(self, *, max_width=None): | ||
| rendered = '(\n{}\n)'.format(',\n '.join(result)) | ||
| if self.return_annotation is not _empty: | ||
| anno = formatannotation(self.return_annotation) | ||
| anno = formatannotation(self.return_annotation, | ||
| quote_annotation_strings=quote_annotation_strings) | ||
| rendered += ' ->{}'.format(anno) | ||
| return rendered | ||
| def signature(obj, *, follow_wrapped=True, globals=None, locals=None, eval_str=False): | ||
| def signature(obj, *, follow_wrapped=True, globals=None, locals=None, eval_str=False, | ||
| annotation_format=Format.VALUE): | ||
| """Get a signature object for the passed callable.""" | ||
| return Signature.from_callable(obj, follow_wrapped=follow_wrapped, | ||
| globals=globals, locals=locals, eval_str=eval_str) | ||
| globals=globals, locals=locals, eval_str=eval_str, | ||
| annotation_format=annotation_format) | ||
| class BufferFlags(enum.IntFlag): | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| def f(x: undefined): | ||
| pass |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| from annotationlib import Format, ForwardRef | ||
| import asyncio | ||
| import builtins | ||
| import collections | ||
| @@ -22,7 +23,6 @@ | ||
| import types | ||
| import tempfile | ||
| import textwrap | ||
| from typing import Unpack | ||
| import unicodedata | ||
| import unittest | ||
| import unittest.mock | ||
| @@ -46,6 +46,7 @@ | ||
| from test.test_inspect import inspect_fodder as mod | ||
| from test.test_inspect import inspect_fodder2 as mod2 | ||
| from test.test_inspect import inspect_stringized_annotations | ||
| from test.test_inspect import inspect_deferred_annotations | ||
| # Functions tested in this suite: | ||
| @@ -4622,6 +4623,18 @@ def func( | ||
| expected_multiline, | ||
| ) | ||
| def test_signature_format_unquote(self): | ||
| def func(x: 'int') -> 'str': ... | ||
| self.assertEqual( | ||
| inspect.signature(func).format(), | ||
| "(x: 'int') -> 'str'" | ||
| ) | ||
| self.assertEqual( | ||
| inspect.signature(func).format(quote_annotation_strings=False), | ||
| "(x: int) -> str" | ||
| ) | ||
| def test_signature_replace_parameters(self): | ||
| def test(a, b) -> 42: | ||
| pass | ||
| @@ -4854,6 +4867,26 @@ def test_signature_eval_str(self): | ||
| par('b', PORK, annotation=tuple), | ||
| ))) | ||
| def test_signature_annotation_format(self): | ||
| ida = inspect_deferred_annotations | ||
| sig = inspect.Signature | ||
| par = inspect.Parameter | ||
| PORK = inspect.Parameter.POSITIONAL_OR_KEYWORD | ||
Member There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🐷 | ||
| for signature_func in (inspect.signature, inspect.Signature.from_callable): | ||
| with self.subTest(signature_func=signature_func): | ||
| self.assertEqual( | ||
| signature_func(ida.f, annotation_format=Format.STRING), | ||
| sig([par("x", PORK, annotation="undefined")]) | ||
| ) | ||
| self.assertEqual( | ||
| signature_func(ida.f, annotation_format=Format.FORWARDREF), | ||
| sig([par("x", PORK, annotation=ForwardRef("undefined"))]) | ||
| ) | ||
| with self.assertRaisesRegex(NameError, "undefined"): | ||
| signature_func(ida.f, annotation_format=Format.VALUE) | ||
| with self.assertRaisesRegex(NameError, "undefined"): | ||
| signature_func(ida.f) | ||
| def test_signature_none_annotation(self): | ||
| class funclike: | ||
| # Has to be callable, and have correct | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
4 changes: 4 additions & 0 deletions 4 Misc/NEWS.d/next/Library/2024-09-27-06-39-32.gh-issue-101552.xYkzag.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| Add an *annoation_format* parameter to :func:`inspect.signature`. Add an | ||
| *quote_annotation_strings* parameter to :meth:`inspect.Signature.format`. Use the | ||
| new functionality to improve the display of annotations in signatures in | ||
| :mod:`pydoc`. Patch by Jelle Zijlstra. |
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.