[issue16694] Add pure Python operator module

Serhiy Storchaka report at bugs.python.org
Sun Dec 16 12:29:26 CET 2012


Serhiy Storchaka added the comment:

Here is a functional (and more effective) equivalent of attrgetter:

def attrgetter(attr, *attrs):
    """
    Return a callable object that fetches the given attribute(s) from its operand.
    After f=attrgetter('name'), the call f(r) returns r.name.
    After g=attrgetter('name', 'date'), the call g(r) returns (r.name, r.date).
    After h=attrgetter('name.first', 'name.last'), the call h(r) returns
    (r.name.first, r.name.last).
    """
    if not attrs:
        if not isinstance(attr, str):
            raise TypeError('attribute name must be a string')
        names = attr.split('.')
        def func(obj):
            for name in names:
                obj = getattr(obj, name)
            return obj
        return func
    else:
        getters = tuple(map(attrgetter, (attr,) + attrs))
        def func(obj):
            return tuple(getter(obj) for getter in getters)
        return func

----------
nosy: +serhiy.storchaka

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue16694>
_______________________________________


More information about the Python-bugs-list mailing list