[Tutor] executing a function in a different file and class

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Aug 22 06:35:05 CEST 2004

> Python doesn't support true golobal variables

[text cut]

> > So how does one make a global truly global?
> Thats such a yucky idea that Python won't let you, but it does provide
> the import controls described above which allow you to fake it on a file
> by file basis.

Hi Vicki,

Actually, it is possible to do something truly ugly here.  It involves
injecting something into the __builtins__ dictionary.

[Warning to others: please do NOT do this in either testing or production

$ cat foo.py
__builtins__['variable'] = "hello"

$ cat bar.py
import foo
print variable

$ python bar.py

This '__builtins__' dictionary houses all of the Python builtins.
Injecting your own variable there should make it visible everywhere. That
being said, using this mechanism casually is almost certainly a Bad Idea.
We show it, reluctantly, only because you asked.  *grin*

It's bad because, if we use this hack frequently, then looking at
code like:

import foo, bar, baz
print variable

there is no really good way of knowing where in the world the definition
of 'variable' came from.  Did it come from 'foo', or 'bar', 'or 'baz'?
Any maintainer of the code will end up having to do global searches for
global variables, and that's just silly: modules are meant to enforce

So don't inject your own variables into __builtins__.

Use the 'from some_module import some_name' mechanism instead, because
it's semantically similar enough to how C's does 'extern', but with the
advantage of documenting which module a 'global' is coming from.

$ cat foo_fixed.py
variable = 'hello'

$ cat bar_fixed.py
from foo_fixed import variable

print variable
$ python bar_fixed.py

Hope this helps!

More information about the Tutor mailing list