Global module variables as default parameters

Steve Holden steve at
Sat Sep 23 03:18:52 CEST 2006

John Hunter wrote:
>>>>>>"Christoph" == Christoph Haas <email at> writes:
>     Christoph> Hi, list...  I wondered if it's possible to use global
>     Christoph> (module) variables as default parameters. A simple
>     Christoph> working example:
>     Christoph> ----------------------------------------
>     Christoph> #!/usr/bin/python
>     Christoph> globalvar = 123
>     Christoph> def test(foo=globalvar): print foo
> kwargs defaults are initialized a module load time, not at function
> call time.  The standard idiom is
> def test(foo=None): 
>     if foo is None: foo = globalvar
>     print foo

That's true when the functions are declared at the outer level of the 
module, but don't overlook the fact that a function can be declared 
inside another function or method call (and even returned as (part of) 
the result of that call).

It would be more accurate to say that the default argument values are 
bound when the def statement is executed.

Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd
Skype: holdenweb
Recent Ramblings

More information about the Python-list mailing list