python - returning a default value

前端 未结 1 1319
抹茶落季
抹茶落季 2020-12-01 19:08

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

相关标签:
1条回答
  • 2020-12-01 19:34

    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 = {}
    
    0 讨论(0)
提交回复
热议问题