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)?
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: