I need to get the type hint as a string. Exactly what it looks like in Pylint.
Example:
def pull_type(tp: type) -> str: ... # CODE
pull_type(Optional[int]) # 'int | None'
pull_type(Union[str, bytes]) # 'str | bytes'
pull_type(str) # 'str'
pull_type(Literal["name", "id", "desc"]) # 'Literal["name", "id", "desc"]'
I spent a lot of time searching, got into pylint, pydoc, astroid (pylint has it as a dependency).
I searched the documentation of each of them.
But as a result I have not found anything useful.
I want to find a ready-made solution rather than creating a whole module to handle Optional, List, Union, Tuple and so on.
>Solution :
One way to achieve this is by using the typing_inspect module, which is a third-party package that provides tools for working with Python’s typing module. You can use the typing_inspect.get_type_hints() function to get the type hints of a given function and then use the typing_inspect.format_type() function to format the type hints as a string in the same format as Pylint.
Here is an example implementation of your pull_type() function using typing_inspect:
from typing import Optional, List, Tuple, Union, Literal
import typing_inspect
def pull_type(tp: type) -> str:
if typing_inspect.is_optional_type(tp):
return f"{pull_type(typing_inspect.get_optional_type(tp))} | None"
elif typing_inspect.is_union_type(tp):
return " | ".join(pull_type(arg) for arg in typing_inspect.get_args(tp))
elif typing_inspect.is_tuple_type(tp):
return f"Tuple[{', '.join(pull_type(arg) for arg in typing_inspect.get_args(tp))}]"
elif typing_inspect.is_list_type(tp):
return f"List[{pull_type(typing_inspect.get_args(tp)[0])}]"
elif typing_inspect.is_literal_type(tp):
return f"Literal[{', '.join(repr(arg) for arg in typing_inspect.get_args(tp))}]"
else:
return tp.__name__
# Example usage
print(pull_type(Optional[int])) # 'int | None'
print(pull_type(Union[str, bytes])) # 'str | bytes'
print(pull_type(str)) # 'str'
print(pull_type(Tuple[int, str, float])) # 'Tuple[int, str, float]'
print(pull_type(List[str])) # 'List[str]'
print(pull_type(Literal["name", "id", "desc"])) # 'Literal["name", "id", "desc"]'
Note that this implementation only handles Optional, Union, Tuple, List, and Literal types, but you can easily extend it to handle other types as well.