When do default parameters get their values set?
Tim Chase
python.list at tim.thechases.com
Mon Dec 8 17:26:31 EST 2014
On 2014-12-08 14:10, 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.
>
> #module name beTest.py
>
> cfg = { 'def' : 'blue'}
>
> def printDef(argT = cfg['def']):
At this point (after the "def" has completed defining the function),
the expression is evaluated and assigned to the default argument.
> 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?
Well, you can bind to a default dictionary rather than an entry in
that dictionary:
cfg = {'def': 'blue'}
def printDef(config=cfg):
...
access(config['def'])
which will make the look-up happen at run-time rather than
definition/bind-time.
beTest.cfg['def'] = 'Red!'
beTest.printDef()
# should print "Red!"
-tkc
More information about the Python-list
mailing list