Defining a default argument as a global variable

后端 未结 1 1750
滥情空心
滥情空心 2020-12-11 19:22

Suppose I have a Python function foo which takes a default argument, where that default is set to some global variable. If I now change that global variable bef

相关标签:
1条回答
  • 2020-12-11 19:51

    A default variable is only evaluated and set once. So Python makes a copy of the reference and from then on, it always passes that reference as default value. No re-evaluation is done.

    You can however solve this by using another object as default object, and then use an if statement to substitute it accordingly. Something like:

    the_default = object()
    x = 1
    
    def foo(a = the_default):
        if a is the_default:
            a = x
        print a
    
    x = 2
    foo()

    Note that we use is to perform reference equality. So we check if it is indeed the default_object. You should not use the the_default object somewhere else in your code.

    In many Python code, they use None as a default (and thus reduce the number of objects the construct). For instance:

    def foo(a = None):
        if a is None:
            a = x
        print a

    Note however that if you do that, your program cannot make a distinction between a user calling foo() and foo(None) whereas using something as the_object makes it harder for a user to obtain a reference to that object. This can be useful if None would be a valid candidate as well: if you want foo(None) to print 'None' and not x.

    0 讨论(0)
提交回复
热议问题