简体   繁体   中英

Return value in generator function Python 2

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM