Why doesn't python have an attrsetter (and what should it do to do this)?

operator provides an attrgetter to create a function that retrieves a field from an object.

Why is this not included in operator (or elsewhere in standard libraries)?

 def attrsetter(name): def setter( obj, val): setattr(obj, name, val) return setter 

The only reason I can think of this is because there are extreme cases where this simple approach will break. In this case, what are these extreme cases so that I can try to catch / avoid them?

+5
source share
1 answer

attrgetter intended for use in places where a function to replace lambda is required. For instance:

 # equivalent heads = map(attrgetter('head'), objs) heads = map(lambda o: o.head, objs) 

In other words, the point of an attrgetter is to create a function without side effects that returns a useful value and that can be used in expressions that require a function. On the other hand, an attrsetter will only act on a side effect and should return None by Python convention. Since an attrsetter would not be generally useful as an argument to map and the like, it is not provided. If you need an attrsetter , just write a regular for loop.

Also note that both of the above idioms are better expressed with list comprehension:

 heads = [o.head for o in objs] 

attrgetter rarely required and has lost most of its appeal once it was announced that lambda would not be removed from Python 3 at the end.

+6
source

Source: https://habr.com/ru/post/1209557/


All Articles