Global module variables as default parameters
Peter Otten
__peter__ at web.de
Fri Sep 22 11:29:11 EDT 2006
Christoph Haas wrote:
> Hi, list...
>
> I wondered if it's possible to use global (module) variables as default
> parameters. A simple working example:
>
> ----------------------------------------
> #!/usr/bin/python
>
> globalvar = 123
>
> def test(foo=globalvar):
> print foo
>
> test()
> ----------------------------------------
>
> Running this script prints "123". That's what I expected.
>
> Now I'm trying the same thing in a module context. A non-working example:
>
> test.py
> ----------------------------------------
> #!/usr/bin/python
>
> import TestModule
>
> TestModule.globalvar = 123
> TestModule.def1()
> TestModule.def2()
> ----------------------------------------
>
> 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?
Yes, and that context is the function definition which is executable code,
too. Whatever the variable 'right' in a statement like
def f(left=right): ...
is bound to when the def is executed will become the default for the 'left'
argument. This should become clear when you create more than one function
with the same
>>> fs = []
>>> for i in range(3):
... def f(i=i): print i
... fs.append(f)
...
>>> for f in fs: f()
...
0
1
2
Use a sentinel when you don't want that behaviour:
def f(foo=None):
if foo is None: foo = globalvar
# ...
Peter
More information about the Python-list
mailing list