Skip to content

Instantly share code, notes, and snippets.

@CodeByAidan
Last active February 7, 2024 00:15
Show Gist options
  • Save CodeByAidan/4e3ee8ebf1796f49f2b826b49cb4155a to your computer and use it in GitHub Desktop.
Save CodeByAidan/4e3ee8ebf1796f49f2b826b49cb4155a to your computer and use it in GitHub Desktop.
Recursively prints the attributes of an object.
def print_attributes(obj: object, indent: int = 0) -> None:
"""
Recursively prints the attributes of an object.
Args:
obj (object): The object to print the attributes of.
indent (int, optional): The number of spaces to indent the output. Defaults to 0.
Returns:
None
Example:
>>> print_attributes({"a": 1, "b": 2})
a: 1
b: 2
>>> class MyClass:
... def __init__(self):
... self.attr1 = "Value 1"
... self.attr2 = 42
... self.attr3 = {"nested_attr": "Nested Value"}
... self.attr4 = [1, 2, 3]
...
>>> print_attributes(MyClass().__dict__)
attr1: Value 1
attr2: 42
attr3:
nested_attr: Nested Value
attr4:
[0]:
1
[1]:
2
[2]:
3
>>> import requests
>>> response = requests.get("https://api.github.com")
>>> print_attributes(response.__dict__)
_content: b'{\n "current_user_url": "https://api.github.com/user", ...}'
_content_consumed: True
_next: None
status_code: 200
headers: {'Server': 'GitHub.com', 'Date': 'Tue, 06 Feb 2024 23:56:57 GMT', ...}
raw: <urllib3.response.HTTPResponse object at 0x000002194432EE00>
url: https://api.github.com/
encoding: utf-8
history:
reason: OK
cookies: <RequestsCookieJar[]>
elapsed: 0:00:00.325808
request: <PreparedRequest [GET]>
connection: <requests.adapters.HTTPAdapter object at 0x0000021944065B10>
"""
# pylint: disable=invalid-name
_GREEN = "\033[32m"
_BLUE = "\033[34m"
_RESET = "\033[0m"
if isinstance(obj, dict):
for key, value in obj.items():
if isinstance(value, (dict, list)):
print(f"{' ' * indent}{_GREEN}{key}{_RESET}:")
print_attributes(value, indent + 4)
else:
print(f"{' ' * indent}{_GREEN}{key}{_RESET}: {_BLUE}{value}{_RESET}")
elif isinstance(obj, list):
for i, item in enumerate(obj):
print(f"{' ' * indent}[{i}]:")
print_attributes(item, indent + 4)
else:
print(f"{' ' * indent}{obj}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment