Generators are lazy evaluated. You need to process a generator in order to your function be evaluated. One can use collections.deque
to consume a generator:
import collections
generator = (myClass().Function(thing) for thing in biggerThing)
collections.deque(generator , maxlen=0)
And consider using @staticmethod
or @classmethod
, or change to
myfunc = myClass().Function
generator = (myfunc(thing) for thing in biggerThing)
collections.deque(generator , maxlen=0)
to reduce new instance of myClass
creation for each thing
processing.
update, performance
collections
vs iteration
def l():
for x in range(100):
y = x**2
yield y
def consume(it):
for i in it:
pass
>>> timeit.timeit('from __main__ import l, consume; consume(l())', number=10000)
0.4535369873046875
>>> timeit.timeit('from __main__ import l, collections; collections.deque(l(), 0)', number=10000)
0.24533605575561523
- instance vs class vs static methods
class Test(object):
@staticmethod
def stat_pow(x):
return x**2
@classmethod
def class_pow(cls, x):
return x**2
def inst_pow(self, x):
return x**2
def static_gen():
for x in range(100):
yield Test.stat_pow(x)
def class_gen():
for x in range(100):
yield Test.class_pow(x)
def inst_gen():
for x in range(100):
yield Test().inst_pow(x)
>>> timeit.timeit('from __main__ import static_gen as f, collections; collections.deque(f(), 0)', number=10000)
0.5983021259307861
>>> timeit.timeit('from __main__ import class_gen as f, collections; collections.deque(f(), 0)', number=10000)
0.6772890090942383
>>> timeit.timeit('from __main__ import inst_gen as f, collections; collections.deque(f(), 0)', number=10000)
0.8273470401763916