Global module variables as default parameters

Christoph Haas email at christoph-haas.de
Fri Sep 22 11:10:28 EDT 2006


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?

Thanks for any enlightenment.

 Christoph



More information about the Python-list mailing list