operator.attrgetter()

operator.attrgetter(attr) operator.attrgetter(*attrs)

Return a callable object that fetches attr from its operand. If more than one attribute is requested, returns a tuple of attributes. The attribute names can also contain dots. For example:

  • After f = attrgetter('name'), the call f(b) returns b.name.
  • After f = attrgetter('name', 'date'), the call f(b) returns (b.name, b.date).
  • After f = attrgetter('name.first', 'name.last'), the call f(b) returns (b.name.first, b.name.last).

Equivalent to:

def attrgetter(*items):
    if any(not isinstance(item, str) for item in items):
        raise TypeError('attribute name must be a string')
    if len(items) == 1:
        attr = items[0]
        def g(obj):
            return resolve_attr(obj, attr)
    else:
        def g(obj):
            return tuple(resolve_attr(obj, attr) for attr in items)
    return g

def resolve_attr(obj, attr):
    for name in attr.split("."):
        obj = getattr(obj, name)
    return obj
doc_python
2016-10-07 17:38:21
Comments
Leave a Comment

Please login to continue.