Defining a default argument as a global variable

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.

Leave a Comment