0

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
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
AJG519
  • 3,249
  • 10
  • 36
  • 62
  • 3
    Why don't you write a wrapper function that calls your generator or standard function? – Aidenhjj Sep 27 '16 at 21:45
  • This should be two functions. – user2357112 Sep 27 '16 at 21:48
  • No, you can't write one function that can somehow toggle between being a function or a generator. If you feel you have an answer, *write an answer*. – jonrsharpe Sep 27 '16 at 21:51
  • Why is the checking being done inside the 'function'? Do the check for needing a generator in the surrounding code. If you need a generator call a generator. If you need a function, call the functional version. – James McCormac Sep 27 '16 at 22:02

1 Answers1

4

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.

Community
  • 1
  • 1
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93