In two lines I can do something like:
for object in object_list:
object.param = 10
Is there any way to do this in one line?
something like:
(object.param = 10) for object in object_list
In two lines I can do something like:
for object in object_list:
object.param = 10
Is there any way to do this in one line?
something like:
(object.param = 10) for object in object_list
This is the typical use case for setattr
and its corresponding "dunder" (double-underscore function) __setattr__
. You can use these in any comprehension (list, dictionary or set) or any generator comprehension.
[setattr(obj,'attr',value)for obj in object_list]
[obj.__setattr__('attr',value)for obj in object_list]
This could also be achieved via combinations of map
and lambda
to avoid the comprehension aspect, though to execute these you would have to iterate through the map. In the example below I've used [*map()]
for this for brevity, but list(map)
is a slightly longer approach which achieves essentially the same thing.
[*map(lambda obj:setattr(obj,'param',value),object_list)]
[*map(lambda obj:obj.__setattr__('attr',value),object_list)]