Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Handle displays
  • Loading branch information
JelleZijlstra committed Apr 22, 2025
commit 3d7fec8d3efac475f988df409d2cf4c899d385f6
24 changes: 24 additions & 0 deletions Lib/annotationlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,30 @@ def __convert_to_ast(self, other):
return other.__ast_node__, other.__extra_names__
elif other is None or type(other) in (str, int, float, bool, complex):
return ast.Constant(value=other), None
elif type(other) is dict:
extra_names = {}
keys = []
values = []
for key, value in other.items():
new_key, new_extra_names = self.__convert_to_ast(key)
if new_extra_names is not None:
extra_names.update(new_extra_names)
keys.append(new_key)
new_value, new_extra_names = self.__convert_to_ast(value)
if new_extra_names is not None:
extra_names.update(new_extra_names)
values.append(new_value)
return ast.Dict(keys, values), extra_names
elif type(other) in (list, tuple, set):
extra_names = {}
elts = []
for elt in other:
new_elt, new_extra_names = self.__convert_to_ast(elt)
if new_extra_names is not None:
extra_names.update(new_extra_names)
elts.append(new_elt)
ast_class = {list: ast.List, tuple: ast.Tuple, set: ast.Set}[type(other)]
return ast_class(elts), extra_names
else:
name = self.__stringifier_dict__.create_unique_name()
return ast.Name(id=name), {name: other}
Expand Down
25 changes: 25 additions & 0 deletions Lib/test/test_annotationlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,31 @@ def f(
},
)

def test_displays(self):
# Simple case first
def f(x: a[[int, str], float]):
pass
anno = annotationlib.get_annotations(f, format=Format.STRING)
self.assertEqual(anno, {"x": "a[[int, str], float]"})

def g(
w: a[[int, str], float],
x: a[{int, str}, 3],
y: a[{int: str}, 4],
z: a[(int, str), 5],
):
pass
anno = annotationlib.get_annotations(g, format=Format.STRING)
self.assertEqual(
anno,
{
"w": "a[[int, str], float]",
"x": "a[{int, str}, 3]",
"y": "a[{int: str}, 4]",
"z": "a[(int, str), 5]",
},
)

def test_nested_expressions(self):
def f(
nested: list[Annotated[set[int], "set of ints", 4j]],
Expand Down
Loading