decorator - Some useful decorators¶
-
args2attrs
(restrict_to=(), exclude=(), expand_kw=True)[source]¶ Decorator to copy method arguments to instance attributes that have the same names (eg: in __init__)
Parameters: Returns: decorator
Return type: func
Example
>>> class my_cls: ... @args2attrs ... def __init__(self, a, b): ... self.total = self.a + self.b >>> inst = my_cls(5,2) >>> inst.a, inst.b, inst.total (5, 2, 7)
-
ordered_by
(*attrs)[source]¶ Class decorator factory for adding comparison methods based on one or more attributes
Parameters: attrs (str) – Name(s) of attribute(s) to use for ordering instances Returns: Function to add comparison methods to the class Return type: func Example
>>> @ordered_by('name') ... class my_cls: ... def __init__(self, name): ... self.name = name ... def __repr__(self): ... return '{}({})'.format(type(self).__name__, repr(self.name)) >>> sorted([my_cls('foo'), my_cls('bar'), my_cls('bax')]) [my_cls('bar'), my_cls('bax'), my_cls('foo')]