2

I have a question regarding converting a yield statement to a generator expression

So I have this small yield method that gets a function and a starting number as its inputs, and basically calls the function for each previous number that was called i.e:

  • The first call returns the initial number
  • The second call returns the function(initial number)
  • The third call returns the function(second number)
  • The fourth call returns the function(third number)

etc. Here is the code in Python:

def some_func(function, number):
    while True:
        yield number
        number = function(number)

What are the ways of converting this snippet into a Generator Expression? I'm guessing that there is a very pythonic and elegant way of doing this, but I just can't get my head around it.

I am quite unfamiliar with Generator Expressions, hence why I'm asking for help but I do want to expand my knowledge of Gen Exp in general and of Python in particular

3
  • 2
    Generator expressions don't really have a "memory" like that local variable, nor can they call themselves recursively. Perhaps I'm going to be surprised by the answers, but it seems to me that your function is already the elegant and Pythonic way to do it. Commented Nov 30, 2013 at 12:21
  • 1
    A generator expression needs a) another iterable to loop over, and b) does not have access to additional variables. I'd stick to the function as is. Commented Nov 30, 2013 at 12:22
  • 1
    You can look at the answers to this question, and wrap (x for x in whatever) around them. Multiple people have been asking variations on the same question recently, although they tended to say "without using yield" and not "use a genexp". Commented Nov 30, 2013 at 14:13

1 Answer 1

5

Stick to what you have now. You could convert the function to a generator expression but it'd be an unreadable mess.

Generator expressions need another iterable to loop over, which your generator function doesn't have. Generator expressions also don't really have access to any other variables; there is just the expression and the loop, with optional if filters and more loops.

Here is what a generator expression would look like:

from itertools import repeat

number = [number]
gen = ((number[0], number.__setitem__(0, function(number[0]))[0] for _ in repeat(True))

where we abuse number as a 'variable'.

Sign up to request clarification or add additional context in comments.

1 Comment

Eek. That's kinda Perl programming in Python... g

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.