Global module variables as default parameters

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Fri Sep 22 11:28:14 EDT 2006


In <mailman.464.1158937836.10491.python-list at python.org>, 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.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list