azrael azrael - 10 months ago 26
Python Question

Is there a built-in way (e.g., a decorator) to instantiate a Python generator at definiton?

Is there a built-in/recommended way to replace the decorator:

def generator(f):
return f()

in the following example?

from random import randint

def mygenerator():
while True:
yield randint(0, 9)

for i in mygenerator:
print i

... as I don't want to write:

for i in mygenerator():
print i

This is a simplified example. In the actual use-case there is no need/reason to have two instances of
, therefore I'd like to create the instance right away. Preferably in a way that no other instance can be created.


The built-in way to do it is like this:

def mygenerator():
    while True:
        yield randint(0, 9)

mygenerator = mygenerator()

This at least has the virtue of being clear, so you don't have to look up what @generator does.