Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneously assign many instances' properties

Suppose I have a class:

class Foo:
    def __init__(self):
        self.prop = None

I need to do:

[foo1.prop, foo2.prop, ..., fooN.prop] = [prop_value1, prop_value2, ..., prop_value3]

Obviously, N is not the same always, so I should do it dynamically. The first approach is do it with a for loop:

for foo, value in zip(foo_list, value_list):
    foo.prop = value

But the question is... Is there a better approach in Python? I mean higher performance.

By the way, N > 1000.

like image 211
Cristhian Boujon Avatar asked May 25 '26 20:05

Cristhian Boujon


1 Answers

"Is there a better approach in Python? I mean higher performance."

I don't believe there is. Let's do a few timed experiments. First, consider an alternative way of performing your assignment: You can use a setter for your class, and call that setter inside a comprehension/map.

class Foo:
    def __init__(self):
        self.prop = None
    def setProp(self, prop):
        self.prop = prop

Now, you can do this:

from functools import partial
f = partial(Foo.setProp)

fooList = [...]
propList = [...]

list(map(f, fooList, propList))

This works as expected. We can use timeit to get some timed results with N = 1000:

  1. For loop approach

10000 loops, best of 3: 95.8 µs per loop

  1. Map approach

1000 loops, best of 3: 199 µs per loop

Conclusion: It seems that the timings differ by a factor of 2. I believe that nothing can beat a for loop for this particular use case, it's a syntax of the language and faster than using any function.

like image 111
cs95 Avatar answered May 27 '26 08:05

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!