Closed simonw closed 1 year ago
I set ChatGPT Code Interpreter to work on this and it found a solution!
https://chat.openai.com/share/b9873d04-5978-489f-8c6b-4b948db7724d
It wrote this code (after a few iterations):
def get_annotation_str(annotation):
"""
Helper function to return the correct string representation of a type annotation.
Args:
annotation (ast.expr): The AST node representing the type annotation.
Returns:
str: The string representation of the type annotation.
"""
if annotation is None:
return ""
elif isinstance(annotation, ast.Name):
return annotation.id
elif isinstance(annotation, ast.Subscript):
value = get_annotation_str(annotation.value)
slice = get_annotation_str(annotation.slice)
return f"{value}[{slice}]"
elif isinstance(annotation, ast.Index):
return get_annotation_str(annotation.value)
elif isinstance(annotation, ast.Tuple):
elements = ", ".join(get_annotation_str(e) for e in annotation.elts)
return f"({elements})"
else:
return "?"
ChatGPT also suggested https://pypi.org/project/astor/ - if I wasn't trying to avoid extra dependencies that would be a really good option.
But it should be:
https://github.com/simonw/symbex/blob/46f8a6d08d825913d12f082b6f510fc37fa86835/symbex/lib.py#L8-L10