python - returning a default value

好久不见. 提交于 2019-11-27 09:16:28

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!")

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.

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

sentinel = []
sentinel = {}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!