Skip to content
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

Correctly parse and cross-reference unpacked type annotations #13369

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions sphinx/domains/python/_annotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ def unparse(node: ast.AST) -> list[Node]:
return [nodes.Text(repr(node.value))]
if isinstance(node, ast.Expr):
return unparse(node.value)
if isinstance(node, ast.Starred):
result = [addnodes.desc_sig_operator('', '*')]
result.extend(unparse(node.value))
return result
if isinstance(node, ast.Invert):
return [addnodes.desc_sig_punctuation('', '~')]
if isinstance(node, ast.USub):
Expand Down
3 changes: 3 additions & 0 deletions sphinx/pycode/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,5 +202,8 @@ def visit_Tuple(self, node: ast.Tuple) -> str:
else:
return '(' + ', '.join(self.visit(e) for e in node.elts) + ')'

def visit_Starred(self, node: ast.Starred) -> str:
return f'*{self.visit(node.value)}'

def generic_visit(self, node: ast.AST) -> NoReturn:
raise NotImplementedError('Unable to parse %s object' % type(node).__name__)
22 changes: 22 additions & 0 deletions tests/test_domains/test_domain_py.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,28 @@ def test_parse_annotation(app):
),
)

doctree = _parse_annotation('*tuple[str, int]', app.env)
assert_node(
doctree,
(
[desc_sig_operator, '*'],
[pending_xref, 'tuple'],
[desc_sig_punctuation, '['],
[pending_xref, 'str'],
[desc_sig_punctuation, ','],
desc_sig_space,
[pending_xref, 'int'],
[desc_sig_punctuation, ']'],
),
)
assert_node(
doctree[1],
pending_xref,
refdomain='py',
reftype='class',
reftarget='tuple',
)


@pytest.mark.sphinx('html', testroot='_blank')
def test_parse_annotation_suppress(app):
Expand Down
1 change: 1 addition & 0 deletions tests/test_pycode/test_pycode_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
'x[:, np.newaxis, :, :]'), # Index, Subscript, numpy extended syntax
('y[:, 1:3][np.array([0, 2, 4]), :]',
'y[:, 1:3][np.array([0, 2, 4]), :]'), # Index, 2x Subscript, numpy extended syntax
('*tuple[str, int]', '*tuple[str, int]'), # Starred
],
) # fmt: skip
def test_unparse(source, expected):
Expand Down
Loading