Global module variables as default parameters
Christoph Haas
email at christoph-haas.de
Sat Sep 23 17:50:03 EDT 2006
Thanks to all who answered.
On Friday 22 September 2006 17:28, Marc 'BlackJack' Rintsch wrote:
> Christoph Haas wrote:
> > TestModule.py
> > ----------------------------------------
> > globalvar = 0
> >
> > def def1():
> > print globalvar
> >
> > def def2(foo=globalvar):
> > print foo
> > ----------------------------------------
> >
> > Running the test.py script prints "123" and "0". So accessing the
> > globalvar in def1() works. But if I try to use the global variable as
> > a default parameter in def2() it uses the default "0". What is the
> > difference between these two? Are there contexts of default
> > parameters?
>
> Default parameters are evaluated *once* when the ``def`` is executed.
> So in `def2` the value of `foo` won't be looked up when calling the
> function as it is already bound to the value 0.
Now that you point me to it it's pretty obvious indeed. I always forget
that the 'def's are executed at load time, too.
Peter/John: in fact I already used a sentinel like you proposed as
a "workaround". So there is just one sensible way to do it. Again.
Kindly
Christoph
More information about the Python-list
mailing list