IUnknown
IUnknown

Reputation: 9829

To execute a generator

Suppose I create a generator of the following form:

e=[(lambda x:2*x)(x) for x in range(10)]

The way to execute and accumulate the results would be :

list([(lambda x:2*x)(x) for x in range(10)])

However,if I am actually performing a cleaning-up operation(maybe file deletion) as follows:

[(lambda x:db.delete(x.path()))(x) for x in self.candidates if x is not None]

What is the convention to execute this - a list really looks odd in this scenario as there is no result I am interested in?

Upvotes: 1

Views: 349

Answers (1)

wim
wim

Reputation: 363354

Just use a plain-old for loop.

for x in self.candidates:
    if x is not None:
        db.delete(x.path())    

List comprehensions and lambdas are needless sophistication here, it's just making your code less readable.

If, in a more appropriate use-case, you actually need to consume a generator you can do this by nomming it into a zero-length deque:

>>> from __future__ import print_function
>>> import collections
>>> g = (print(x) for x in 'potato')
>>> _ = collections.deque(g, maxlen=0)
p
o
t
a
t
o

Upvotes: 2

Related Questions