Added support for `slice` objects in subscriptions (#11981)

Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
This commit is contained in:
MatrixEditor
2024-02-14 14:45:30 +01:00
committed by GitHub
parent 2fe103acda
commit 182053198d
5 changed files with 38 additions and 0 deletions

View File

@@ -27,6 +27,9 @@ Features added
* #11892: Improved performance when resolving cross references in cpp domain.
Patch by Rouslan Korneychuk.
* #11981: Improve rendering of signatures using ``slice`` syntax,
e.g., ``def foo(arg: np.float64[:,:]) -> None: ...``.
Bugs fixed
----------

View File

@@ -156,6 +156,20 @@ class _UnparseVisitor(ast.NodeVisitor):
def visit_Set(self, node: ast.Set) -> str:
return "{" + ", ".join(self.visit(e) for e in node.elts) + "}"
def visit_Slice(self, node: ast.Slice) -> str:
if not node.lower and not node.upper and not node.step:
# Empty slice with default values -> [:]
return ":"
start = self.visit(node.lower) if node.lower else ""
stop = self.visit(node.upper) if node.upper else ""
if not node.step:
# Default step size -> [start:stop]
return f"{start}:{stop}"
step = self.visit(node.step) if node.step else ""
return f"{start}:{stop}:{step}"
def visit_Subscript(self, node: ast.Subscript) -> str:
def is_simple_tuple(value: ast.expr) -> bool:
return (

View File

@@ -17,3 +17,6 @@ partial_coroutinefunc = partial(coroutinefunc)
builtin_func = print
partial_builtin_func = partial(print)
def slice_arg_func(arg: 'float64[:, :]'):
pass

View File

@@ -199,3 +199,14 @@ def test_async_generator(app):
' :async:',
'',
]
@pytest.mark.sphinx('html', testroot='ext-autodoc')
def test_slice_function_arg(app):
actual = do_autodoc(app, 'function', 'target.functions.slice_arg_func')
assert list(actual) == [
'',
'.. py:function:: slice_arg_func(arg: float64[:, :])',
' :module: target.functions',
'',
]

View File

@@ -51,6 +51,13 @@ from sphinx.pycode.ast import unparse as ast_unparse
"lambda x=0, /, y=1, *args, z, **kwargs: ..."), # posonlyargs
("0x1234", "0x1234"), # Constant
("1_000_000", "1_000_000"), # Constant
("Tuple[:,:]", "Tuple[:, :]"), # Index, Subscript, 2x Slice
("Tuple[1:2]", "Tuple[1:2]"), # Index, Subscript, Slice(no-step)
("Tuple[1:2:3]", "Tuple[1:2:3]"), # Index, Subscript, Slice
("x[:, np.newaxis, :, :]",
"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
])
def test_unparse(source, expected):
module = ast.parse(source)