operator
provides attrgetter
to make a function that retrieves a field from an object.
Why isn't this included in operator
(or somewhere else in the standard libraries)?
def attrsetter(name):
def setter( obj, val):
setattr(obj, name, val)
return setter
The only reason that I can think of is that there are edge cases where this straightforward approach will break. In which case, what are these edge cases so that I can try to trap/avoid them?
attrgetter
is designed to be used in places where a function is required as a replacement for lambda
. For example:
# equivalent
heads = map(attrgetter('head'), objs)
heads = map(lambda o: o.head, objs)
In other words, the point of attrgetter
is to create a side-effect-free function that returns a useful value, and which can be used in expressions that require a function. An attrsetter
, on the other hand, would only operate by side effect, and would need to return None
by Python convention. Since attrsetter
would not be at all useful as argument to map
and similar, it is not provided. If you need attrsetter
, simply write a normal for
loop.
Also note that both of the above idioms are better expressed with a list comprehension:
heads = [o.head for o in objs]
attrgetter
is rarely needed and has lost much of its appeal once it was decided that lambda
would not be removed from Python 3 after all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With