2

So i'm reading Alex Martelli's answer to other question...

"One example in which I may want initialization is when at package-load time I want to read in a bunch of data once and for all (from files, a DB, or the web, say) -- in which case it's much nicer to put that reading in a private function in the package's init.py rather than have a separate "initialization module" and redundantly import that module from every single real module in the package..."

Unfortunately, when i try this:

foo/__init__.py

import tables as tb
global foo
foo = tb.openFile('foo.h5', etc._)
import bar

foo/bar/__init__.py

import tables as tb
global bar
bar = foo.createGroup('/', bar)
import MyFunction`

foo/bar/MyFunction.py

def MyFunction(*of foo and bar*):
   '...'

>>> import foo
>>> OUTPUT= foo.bar.MyFunction.MyFunction(INPUT)
>>> bar = foo.createGroup('/', bar)
NameError: name 'foo' is not defined

How does one define global variables without putting them in a function (as seen here)?

Community
  • 1
  • 1
Noob Saibot
  • 4,573
  • 10
  • 36
  • 60
  • All you have to do when pasting code is indent it by four spaces. There's even a button (with a keyboard shortcut) to do it for you. – Marcelo Cantos Nov 08 '12 at 01:02
  • @Marcelo Cantos I tried, believe me. I don't know what it is about formatting on this thing, but it never seems to want to cooperate with me. – Noob Saibot Nov 08 '12 at 01:37

1 Answers1

2

global variables are not global in the sense that every bit of python code sees the same set of globals. the global-ness is really just the 'module scope'; All of the variables and functions defined in a module are already global, and as global as they can possibly be.

If you want to see the variables defined in one module among the globals of another module, the only way to do it is to import the names of the first module into the second... IE:

# myModule.py
foo = "bar"
# yourModule.py
from myModule import foo
SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304