Reputation: 3379
I'm wondering how I can write a generator function that also has the option to return a value. In Python 2, you get the following error message if a generator function tries to return a value. SyntaxError: 'return' with argument inside generator
Is it possible to write a function where I specify if I want to receive a generator or not?
For example:
def f(generator=False):
if generator:
yield 3
else:
return 3
Upvotes: 0
Views: 1003
Reputation: 23243
Mandatory reading: Understanding Generators in Python
Key information:
yield
anywhere in a function makes it a generator.
Function is marked as generator when code is parsed. Therefore, it's impossible to toggle function behavior (generator / not generator) based on argument passed in runtime.
Upvotes: 4