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:
  • restrict_to (str or iterable) – if specified, only include these named arguments
  • exclude (str or iterable) – names of arguments to exclude from copying (even if they’re in include)
  • expand_kw (bool) – make an individual attribute for each variable keyword argument
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')]