Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't python have a attrsetter (and what would it take to make one)?

Tags:

python

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?

like image 499
Dave Avatar asked Dec 19 '14 15:12

Dave


1 Answers

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.

like image 156
user4815162342 Avatar answered Nov 15 '22 20:11

user4815162342