0

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
pongoS
  • 316
  • 1
  • 3
  • 14

1 Answers1

-1

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)]

Mous
  • 953
  • 3
  • 14
  • No, this is not the typical use-case for `setattr`. – chepner Feb 07 '23 at 21:20
  • @chepner right, `setattr()` is just the workaround for not being able to use walrus as in my attempted solution. – Barmar Feb 07 '23 at 21:22
  • In general you should not use a dunder method directly when you can use the corresponding function. The dunder method is intended for classes to define in order to customize the behavior of the function. – Barmar Feb 07 '23 at 21:24
  • The dunder method is included for demonstration and learning purposes for the OP. – Mous Feb 07 '23 at 21:24
  • That is, `setattr` is not intended to be used just so you can abuse the list comprehension for iteration purposes. You don't want a list full of `None` values created by `setattr`. – chepner Feb 07 '23 at 21:26
  • The `map` versions are particularly grotesque. It's the list you don't want; it doesn't matter if you use an unpacked `map` or a list comprehension to produce it. – chepner Feb 07 '23 at 21:27
  • In this case the expression is intended to be on a line itself. – Mous Feb 07 '23 at 21:30