可选的yield或return in python3.如何? [英] Optional yield or return in python3. How to?

查看:94
本文介绍了可选的yield或return in python3.如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拥有一个可以选择返回或产生结果的函数. 这是一个例子.

I would like to have a function that can, optionally, return or yield the result. Here is an example.

def f(option=True):
    ...
    for...:
        if option:
            yield result
        else:
            results.append(result)

    if not option:
        return results

当然,这是行不通的,我尝试使用python3,并且无论设置什么选项值,我总会得到一个生成器. 据我了解,python检查函数的主体,如果存在yield,则结果将是生成器. 有什么方法可以解决这个问题,并使函数可以随意返回或屈服吗?

Of course, this doesn't work, I have tried with python3 and I always get a generator no matter what option value I set. As far I have understood, python checks the body of the function and if a yield is present, then the result will be a generator. Is there any way to get around this and make a function that can return or yield at will?

推荐答案

您不能. 任何使用yield可使函数生成器.

You can't. Any use of yield makes the function a generator.

您可以将函数包装为使用list()的函数,该函数将生成器生成的所有值存储在列表对象中并返回:

You could wrap your function with one that uses list() to store all values the generator produces in a list object and returns that:

def f_wrapper(option=True):
    gen = f()
    if option:
        return gen    # return the generator unchanged
    return list(gen)  # return all values of the generator as a list

但是,一般来说,这是不良设计.不要让您的函数改变这种行为;坚持使用一种返回类型(生成器对象),并且不要在两者之间切换.

However, generally speaking, this is bad design. Don't have your functions alter behaviour like this; stick to one return type (a generator or an object) and don't have it switch between the two.

请考虑将其分为两个功能:

Consider splitting this into two functions instead:

def f():
    yield result

def f_as_list():
    return list(f())

,如果需要生成器,请使用f(),如果要使用列表,请使用f_as_list().

and use either f() if you need the generator, and f_as_list() if you want to have a list instead.

由于list()(和next()仅访问生成器的一个值)是内置函数,因此您几乎不需要使用包装器.只需直接调用这些函数即可:

Since list(), (and next() to access just one value of a generator) are built-in functions, you rarely need to use a wrapper. Just call those functions directly:

# access elements one by one
gen = f()
one_value = next(gen)

# convert the generator to a list
all_values = list(f())

这篇关于可选的yield或return in python3.如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆