Search code examples
pythonlanguage-featurescorecursion

Python: Create Generators at Runtime


I know in python classes and functions can be created at runtime using type and lambda respectively, but can generators be created at runtime?

Example: keyword, condition, action, yield

lambda x,a: a<x,a++,a


Solution

  • Is this what you are asking for? If by defined at runtime, you mean, without having to explicitly create a function that uses the yield keyword, then yes, you can use generator expressions.

    >>> t = [1, 2, 3]
    >>> (i*2 for i in t)
    <generator object <genexpr> at 0x7f1f72dbfdc0>