Skip to content Skip to sidebar Skip to footer

Defining A Default Argument As A Global Variable

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 before calling the func

Solution 1:

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 = 1deffoo(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:

deffoo(a = None):
    if a isNone:
        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.

Post a Comment for "Defining A Default Argument As A Global Variable"