When do default parameters get their values set?

Dave Angel dave.angel at 1
Tue Dec 9 11:32:01 EST 2014


  To: bSneddon
On 12/08/2014 05:10 PM, bSneddon 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.
>

To answer the subject line, the default parameter(s) are evaluated when
the function is compiled, and then stored with the function.  So in this
case the default for argT is an immutable string "blue"  Being
immutable, nothing will change that for the run of the program.

> #module name beTest.py
>
> cfg = { 'def' : 'blue'}
>
> def printDef(argT = cfg['def']):
> 	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?
>

You're not making a local copy of any dictionary.  The symptoms you have
would be identical even if you run beTest.py directly (with those two
lines added, of course).

The RIGHT approach depends on what your goal is here.  Obviously this is
simplified from some more complex use, but you haven't stated what your
desires are, so I don't necessarily know how to achieve them.

There is only one dictionary, and it does change when you you say:
    beTest.cfg['def'] = "no red"

But if you need to do a lookup in that dictionary upon calling
primtDef(), then you're going to make the evaluation at that time, not
at default-time.

How about the following, fairly common idiom for default values:

def printDef(argT = None]):
     if argT = None:
         argT = cfg['def']
     print argT





--
DaveA

--- SoupGate-Win32 v1.05
 * Origin: <SpaceSST.BBS.Fidonet<>NNTP.gateway. at .piz.noip.me> (1:249/999)
--- Synchronet 3.15b-Win32 NewsLink 1.92
SpaceSST BBS Usenet <> Fidonet Gateway



More information about the Python-list mailing list