python-返回默认值 [英] python - returning a default value

查看:121
本文介绍了python-返回默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找模仿内置函数(例如 getattr )的行为,这些函数允许用户指定默认返回值。我最初的尝试是这样做

I'm looking to mimic the behavior of built-in functions (like getattr) that allow the user to specify a "default" return value. My initial attempt was to do this

def myfunc(foo, default=None):
    # do stuff
    if (default is not None):
        return default
    raise SomeException()

问题是,如果用户希望 None 作为其返回值,则此函数将引发异常。第二次尝试:

The problem is that if the users wants None to be their return value, this function would instead raise an exception. second attempt:

def myfunc(foo, **kwargs):
    # do stuff
    if ('default' in kwargs):
        return kwargs['default']
    raise SomeException()

这解决了上述问题,并允许用户指定任意值,但带来的麻烦是,用户必须始终在其函数中指定 default = bar 电话;他们不能只是在结尾处提供 bar 。同样,可以使用 * args ,但是如果用户喜欢该语法,则可以阻止用户使用 default = bar

This addresses the above issue and allows the user to specify any arbitrary value, but introduces an annoyance in that the user must always specify default=bar in their function calls; they can't just provide bar at the end. Likewise, *args could be used, but prevents users from using default=bar if they prefer that syntax.

结合 * args ** kwargs 提供了一个可行的解决方案,但感觉这需要付出很多努力。它还可能掩盖不正确的函数调用(例如 bar = myfunc(foo,baz,default = qux)

Combining *args and **kwargs provides a workable solution, but it feels like this is going to a lot of effort. It also potentially masks improper function calls (eg bar = myfunc(foo, baz, default=qux))

def myfunc(foo, *args, **kwargs):
    # do stuff
    if (len(args) == 1):
        return args[0]
    if ('default' in kwargs):
        return kwargs['default']
    raise SomeException()

有没有更简单的解决方案? (如果需要的话,则为python 3.2)

Is there a simpler solution? (python 3.2 if that matters)

推荐答案

您需要使用哨兵来检测未设置默认值:

You need to use a sentinel to detect that a default value was not set:

sentinel = object()

def func(someparam, default=sentinel):
    if default is not sentinel:
        print("You passed in something else!")

此之所以有效,是因为 object()的实例将始终具有其自己的内存ID,因此 is 仅在以下情况下返回True:精确值留在原地。 任何其他值都不会注册为同一对象,包括

This works because an instance of object() will always have it's own memory id and thus is will only return True if the exact value was left in place. Any other value will not register as the same object, including None.

您会在各种不同的python项目中看到上述技巧的不同变体。以下任何一个哨兵也可以使用:

You'll see different variants of the above trick in various different python projects. Any of the following sentinels would also work:

sentinel = []
sentinel = {}

这篇关于python-返回默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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