You'll find in the logilab.common.decorators module the iclassmethod decorator which may be pretty handy in some cases as it allows methods to be both called as class methods or as instance methods. In the first case the first argument will be the class and the second case it will be the instance.
Example extracted (and adapted for simplicity) from CubicWeb:
from logilab.common.decorators import iclassmethod class Form(object): _fields_ = [] def __init__(self): self.fields = list(self._fields_) @iclassmethod def field_by_name(cls_or_self, name): """return field with the given name and role""" if isinstance(cls_or_self, type): fields = cls_or_self._fields_ else: fields = cls_or_self.fields for field in fields: if field.name == name: return field raise Exception('FieldNotFound: %s' % name)
Example session:
>>> from logilab.common import attrdict >>> f = Form() >>> f.fields.append(attrdict({'name': 'something', 'value': 1}) >>> f.field_by_name('something') {'name': 'something', 'value': 1} >>> Form.field_by_name('something') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 15, in field_by_name Exception: FieldNotFound: something
So we get a field_by_name method which will act differently (actually use different input data) when called as instance method or as class method.
Also notice the attrdict trick that can also be achieved with the Python 2.6 named tuple.
blog entry of
similar entities
- Discovering logilab-common Part 1 - deprecation module
- The Python Package Index is not a "Software Distribution"
- qgpibplotter is (hopefully) working
- pyreverse http://www.logilab.org/project/pylint a set of tools for reverse engineering Python code.
- logilab-xmltools High level tools to help using XML in Python
[see all]