Skip to content

Instantly share code, notes, and snippets.

@ubershmekel
Created October 27, 2015 17:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ubershmekel/6cfd1d1aafee0253b43b to your computer and use it in GitHub Desktop.
Save ubershmekel/6cfd1d1aafee0253b43b to your computer and use it in GitHub Desktop.
Simple repr methods that allow you to reconstruct a simple object
"""
These two repr implementations make a "repr" that you can just drop into your class if it's a simple one.
"""
class A:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "%s(**%r)" % (self.__class__.__name__, self.__dict__)
print A(1,3)
# A(**{'y': 3, 'x': 1})
class B:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
ctor_str = ', '.join('%s=%r' % pair for pair in (self.__dict__.items()))
return "%s(%s)" % (self.__class__.__name__, ctor_str)
print B(1,3)
# B(y=3, x=1)
@TonyFlury
Copy link

The repr string it generates will only be correct if the class doesn't create it's own Data instance attribute - as all attributes go into self.dict. A full solution would need to use something like the inspect module to look at the arguments in the init method - an interesting programming challenge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment