Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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