Created
March 5, 2017 05:15
-
-
Save egregius313/4d4a39cbf9c5e6dd8e943322c68a47b6 to your computer and use it in GitHub Desktop.
A simple class decorator to define the __repr__ method based on the signature of the __init__ method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A simple class decorator to define the __repr__ method | |
based on the signature of the __init__ method. | |
""" | |
__author__ = 'egregius313' | |
_repr_template = """ | |
def __repr__(self): | |
'Return repr(self)' | |
return '{cls}({kwarg_pairs})'.format( | |
cls=self.__class__.__name__, | |
kwarg_pairs=%s | |
) | |
""" | |
def init_repr(cls): | |
""" | |
Define __repr__ based on the call signature of __init__. | |
Meant for simple types whose __init__ is | |
>>> @init_repr | |
... class Person: | |
... def __init__(self, name, age): | |
... self.name = name | |
... self.age = age | |
... | |
>>> Person('Ed', 18) | |
Person(name='Ed', age=18) | |
""" | |
signature = inspect.signature(cls.__init__) | |
parameters = list(signature.parameters.keys())[1:] | |
kwargs = "', '.join('%s=%r' % (field, getattr(self, field)) for field in {fields})" | |
exec(_repr_template % kwargs.format(fields=parameters)) | |
setattr(cls, '__repr__', eval('__repr__')) | |
return cls |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment