Global module variables as default parameters

Marc 'BlackJack' Rintsch bj_666 at
Fri Sep 22 17:28:14 CEST 2006

In <mailman.464.1158937836.10491.python-list at>, Christoph Haas

> ----------------------------------------
> globalvar = 0
> def def1():
>   print globalvar
> def def2(foo=globalvar):
>   print foo
> ----------------------------------------
> Running the 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.

	Marc 'BlackJack' Rintsch

More information about the Python-list mailing list