Declarative Generation#
Helper Mixin#
If you cannot use, or prefer not to use ReprMixin
,
there is an alternative declarative syntax.
ReprHelperMixin
provides __repr__
,
_repr_pretty_
(for IPython.lib.pretty
), and __rich_repr__
(for
rich.pretty
), all of which use a user defined function called
_repr_helper_
.
All possible method calls on the passed object r are shown here:
def _repr_helper_(self, r):
r.positional_from_attr('attrname')
r.positional_with_value(value)
r.keyword_from_attr('attrname')
r.keyword_from_attr('keyword', 'attrname')
r.keyword_with_value('keyword', value)
The passed object, r, is a ReprHelper
or
PrettyReprHelper
instance, depending on whether
__repr__
or _repr_pretty_
was called. These classes have an
identical API after instantiation (which is handled by the mixin class).
1from datetime import datetime
2from IPython.lib.pretty import pprint
3from represent import ReprHelperMixin
4
5
6class ContrivedExample(ReprHelperMixin, object):
7 def __init__(self, description, radians, shape, color, miles, cls):
8 self.description = description
9 self.degrees = radians * 180 / 3.141592654
10 self.shape = shape
11 self._color = color
12 self.km = 1.60934 * miles
13 self.cls = cls
14
15 def _repr_helper_(self, r):
16 r.positional_from_attr('description')
17 r.positional_with_value(self.degrees * 3.141592654 / 180)
18 r.keyword_from_attr('shape')
19 r.keyword_from_attr('color', '_color')
20 r.keyword_with_value('miles', self.km / 1.60934)
21 qual_name = '{cls.__module__}.{cls.__name__}'.format(cls=self.cls)
22 r.keyword_with_value('cls', qual_name, raw=True)
23
24
25 ce = ContrivedExample('something', 0.345, 'square', 'red', 22, datetime)
26
27 print(ce)
28 pprint(ce)
ContrivedExample('does something', 0.345, shape='square', color='red', miles=22.0, cls=datetime.datetime)
ContrivedExample('does something',
0.345,
shape='square',
color='red',
miles=22.0,
cls=datetime.datetime)
Note that raw=True
on line 22 presents the string without quotes, because
cls='datetime.datetime'
would be incorrect.
Manual Helpers#
To use the declarative style without using
ReprHelperMixin
, refer to the documentation for
ReprHelper
,
PrettyReprHelper
, and
RichReprHelper
.