Global module variables as default parameters
Steve Holden
steve at holdenweb.com
Fri Sep 22 21:18:52 EDT 2006
John Hunter wrote:
>>>>>>"Christoph" == Christoph Haas <email at christoph-haas.de> 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
>
> JDH
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.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
More information about the Python-list
mailing list