Skip to content

Instantly share code, notes, and snippets.

@CodeByAidan
Last active August 2, 2024 18:12
Show Gist options
  • Select an option

  • Save CodeByAidan/ebce8fb725dc45a04b329d74343a18c5 to your computer and use it in GitHub Desktop.

Select an option

Save CodeByAidan/ebce8fb725dc45a04b329d74343a18c5 to your computer and use it in GitHub Desktop.
Pretty Print a repr() with types in Python, to get those type annotations!
def pretty_repr_types[
K, V: dict | list | str | int # type: ignore - dict and list expect type arguments (pyright)
](obj: dict[K, V] | list[V] | str | int, indent: int = 0) -> str:
"""Recursively prints the types of keys and values in a dictionary."""
spacing: str = " " * indent
if isinstance(obj, dict) and not isinstance(obj, str):
result = "{\n"
for key, value in obj.items():
key_type: str = repr(type(key))
value_repr: str = pretty_repr_types(value, indent + 2)
result += f"{spacing} {key_type}: {value_repr},\n"
result += spacing + "}"
elif isinstance(obj, list) and not isinstance(obj, str):
result = "[\n"
for item in obj:
item_repr: str = pretty_repr_types(item, indent + 2)
result += f"{spacing} {item_repr},\n"
result += f"{spacing}]"
else:
result: str = repr(type(obj))
return result
def pretty_repr_types[
K, V: dict | list | str | int # type: ignore - dict and list expect type arguments (pyright)
](obj: dict[K, V] | list[V] | str | int, indent: int = 0) -> str:
"""Recursively prints the types of keys and values in a dictionary."""
spacing: str = " " * indent
if isinstance(obj, dict) and not isinstance(obj, str):
result = "{\n"
for key, value in obj.items():
key_type: str = repr(type(key))
value_repr: str = pretty_repr_types(value, indent + 2)
result += f"{spacing} {key_type}: {value_repr},\n"
result += spacing + "}"
elif isinstance(obj, list) and not isinstance(obj, str):
result = "[\n"
for item in obj:
item_repr: str = pretty_repr_types(item, indent + 2)
result += f"{spacing} {item_repr},\n"
result += f"{spacing}]"
else:
result: str = repr(type(obj))
return result
example_dict: dict[str, str | int | list[str | dict[str, list[str]]]] = {
"name": "Alice",
"age": 30,
"hobbies": [
"reading",
{
"books": ["The Great Gatsby", "1984"],
},
"hiking",
"coding",
],
}
example_list: list[str | int] = ["apple", "banana", 42, "cherry"]
example_str = "Hello, World!"
example_int = 12345
print(pretty_repr_types(example_dict), end="\n\n")
print(pretty_repr_types(example_list), end="\n\n")
print(pretty_repr_types(example_str), end="\n\n")
print(pretty_repr_types(example_int))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment