Skip to content

Instantly share code, notes, and snippets.

@treyhunner
Created November 4, 2021 19:32
Show Gist options
  • Save treyhunner/7adcbc96870b79642f1754c3cc602ac6 to your computer and use it in GitHub Desktop.
Save treyhunner/7adcbc96870b79642f1754c3cc602ac6 to your computer and use it in GitHub Desktop.
Example of sorting a dictionary of attributes by keys
def easy_repr(obj):
"""
Function to find the type of an object and its attributes
Example:
>>> class Point:
... def __init__(self, x, y, z, color=None):
... self.x, self.y, self.z = x, y, z
... self.color = color
...
>>> p = Point(1, 2, 3)
>>> p
<__main__.Point object at 0x7f55121a6d70>
>>> print(easy_repr(p))
<Point object with attributes {'color': None, 'x': 1, 'y': 2, 'z': 3}>
"""
name = type(obj).__name__
attrs = dict(sorted(obj.__dict__.items()))
return f"<{name} object with attributes {attrs}>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment