When do default parameters get their values set?

Chris Kaynor ckaynor at zindagigames.com
Mon Dec 8 17:28:18 EST 2014


On Mon, Dec 8, 2014 at 2:10 PM, bSneddon <w.g.sneddon at gmail.com> wrote:

> I ran into an issue setting variables from a GUI module that imports a
> back end module.  My approach was wrong obviously but what is the best way
> to set values in a back end module.
>
> #module name beTest.py
>
> cfg = { 'def' : 'blue'}
>
> def printDef(argT = cfg['def']):

        print argT


Here is your problem. The default argument value is evaulated at the time
the function is defined, not when it is called, so argT will boung to
'blue' by default, unless overridden in the call.
In this simple case, you could just change the function to:

def printDef():
    print cfg['def']

In more complicated cases, where you actually need to pass in the argument
with a default, the best way is to use a sentinel value (I'm using None in
the case):

def printDef(argT = None):
    argT = argT or cfg['def'] # If argT could be False or another "falsy"
value, use "argT = argT if argT is not None else cfg['def']". This is also
useful if None needs to be a valid value.
    print argT


>
>
> #module name feTest
> import beTest
>
> beTest.cfg['def'] = "no red"
> beTest.printDef()
>
>
>
> This prints blue.      I suppose because I am changing a local copy of cfg
> dictionary.  What is the write approach here?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20141208/e9df3f5e/attachment.html>


More information about the Python-list mailing list