After creating a start of a function that converts the Annotation type back into a type:
@typechecked
def extract_type_from_annotation(
*,
annotation: Union[
Subscript, Index, Name, Annotation, Attribute, BinaryOperation
],
) -> str:
"""Extract the type information from an annotation.
Args:
annotation (Union[Subscript, Index, Name, Annotation]): The annotation
to extract the type from.
Returns:
str: The extracted type information.
"""
if isinstance(annotation, Subscript):
# Handle the case where the annotation is a Subscript
value = extract_type_from_annotation(annotation=annotation.value)
slice_elements = [
extract_type_from_annotation(annotation=slice_element.slice)
for slice_element in annotation.slice
]
return f"{value}[{', '.join(slice_elements)}]"
if isinstance(annotation, Index):
something = extract_type_from_annotation(annotation=annotation.value)
return something
if isinstance(annotation, Name):
return str(annotation.value)
if isinstance(annotation, Annotation):
something = extract_type_from_annotation(
annotation=annotation.annotation
)
return something
if isinstance(annotation, Attribute):
left = extract_type_from_annotation(annotation=annotation.value)
right = extract_type_from_annotation(annotation=annotation.attr)
something = f"{left}.{right}"
return something
if isinstance(annotation, BinaryOperation):
left = extract_type_from_annotation(annotation=annotation.left)
right = extract_type_from_annotation(annotation=annotation.right)
something = f"{left}.{right}"
return annotation
return str(annotation)
I felt I was re-inventing the wheel. I expect this functionality is already built into LibCST, however, I have some difficulties finding it. After looking at these
I had some difficulties applying it to the Annotation
object like:
code = Module([]).code_for_node(
param.Annotation
)
As that would throw:
libcst._nodes.base.CSTCodegenError: Must specify a concrete default_indicator if default used on indicator.
Question
How to get the type of the parameter Annotation object in LibCST back into a sting of the type?