API Documentation

prettyclass.prettyclass(cls: Type = None, *, init: bool = True, repr: bool = True, copy: bool = True, eq: bool = False, nonzero: bool = False, hash: bool = False, json: bool = False)[source]

pretty class decorator

Returns the same class as was passed in, with dunder methods added based on the fields defined in the ‘__init__’ signature .

Parameters:
  • cls – class to add methods

  • init – add ‘__init__’ method body by storing all arguments of its signature, so they are available for the added methods but are not needed to be implemented (optional; default is True)

  • repr – bool to add ‘__repr__’ and ‘__str__’ (optional; default is True)

  • copy – bool to add ‘__copy__’ as well as ability to pickle (optional; default is True)

  • eq – bool to add ‘__eq__’ which then returns True if all arguments fields are equal (optional; default is False)

  • nonzero – bool to add ‘__bool__’ which then returns True if all arguments fields are True (optional; default is False)

  • hash – bool to add ‘__hash__’ which then returns hash(repr(self.__dict__)) (optional; default is False)

  • json – bool to add ‘__json__’ and classmethod ‘from_json’ to serialize and de-serialize json strings (optional; default is False)

Returns:

same class

It is recommended to avoid any further attributes which define the state of an instance. Otherwise, the instance replication would not be ensured.

>>> from prettyclass import prettyclass
>>> @prettyclass()
... class ABC:
...     def __init__(self, a, *b, c, d=1, e, **f):
...         '''creates ABC instance'''

The decorator adds automaticly all argument fields as attributes.

>>> abc = ABC(1, 2, [3, 4], c=5, d=6, e=7, g='A', h='B')
>>> abc.__dict__
{'a': 1, 'b': (2, [3, 4]), 'c': 5, 'd': 6, 'e': 7, 'f': {'g': 'A', 'h': 'B'}}
>>> abc.a, abc.b, abc.c, abc.d, abc.e, abc.f
(1, (2, [3, 4]), 5, 6, 7, {'g': 'A', 'h': 'B'})

and returns a pretty nice representation of an instance

>>> abc
ABC(1, 2, [3, 4], c=5, d=6, e=7, g='A', h='B')

Note the difference between ‘str’ and ‘repr’

>>> str(abc)
'ABC(1, 2, [3, 4], c=5, d=6, e=7, g=A, h=B)'
>>> repr(abc)
"ABC(1, 2, [3, 4], c=5, d=6, e=7, g='A', h='B')"

Copy works by default, too.

>>> from copy import copy
>>> copy(abc)
ABC(1, 2, [3, 4], c=5, d=6, e=7, g='A', h='B')

Same for pickle.

>>> from pickle import dumps, loads
>>> s = dumps(abc)  
>>> loads(s)  
ABC(1, 2, [3, 4], c=5, d=6, e=7, g='A', h='B')

Note, the string representation ommitts entries which coincide with defaults

>>> ABC(1, 2, [3, 4], c=5, d=1, e=7, g='A', h='B')
ABC(1, 2, [3, 4], c=5, e=7, g='A', h='B')