stantonk
stantonk

Reputation: 2010

Setting attributes on object instances in Python via map builtin

There's got to be a way to do this with map()

This:

for inst in list_of_instances:
    inst.run()

Can be done like this:

map(operator.methodcaller('run'), list_of_instances)

How can this be done with map()?

for inst in list_of_instances:
    inst.some_setting = True

Upvotes: 1

Views: 130

Answers (2)

Lambda Fairy
Lambda Fairy

Reputation: 14676

You can, but it's not a good idea.

map is designed to work only with pure (immutable) operations, i.e. functions that return a new object. The lack of an itemsetter function reflects this idea. Since your code modifies objects in place, you should use a for loop instead.

This is important because in Python 3, map doesn't return a list. It returns an iterator object, which calls your function on demand. So under Python 3, your code won't run at all.

The map vs for distinction isn't unique to Python. In JavaScript, you have map and forEach; in Haskell, you have map and traverse. It's important to distinguish between these two fundamentally different things.

Upvotes: 2

falsetru
falsetru

Reputation: 369054

You can use setattr:

map(lambda inst: setattr(inst, 'some_setting', True), list_of_instances)

or using list comprehension:

[setattr(inst, 'some_setting', True) for inst in list_of_instances]

BTW, I think simple for loop is better than map because

  • for loop is easier to read.
  • map, list comprehension versions generate temporary list ([None, None, None, ..., None])

Upvotes: 4

Related Questions