[Tutor] quick query relating to globals (I think)

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 23 Jun 2002 22:52:42 -0700 (PDT)


On Mon, 24 Jun 2002, Glen Edward Wheeler wrote:

>   I'm making a program with a whole bunch of modules in different files
> (as you do) and I'm wondering if it's possible to make an instance of a
> class in one of those modules accessible by all the other modules...how
> 'bout an example to illustrate :-
>
> main.py
> one.py
> two.py
> thing.py -> has class thing in it
>
> main calls one and two, main also initialises an instance of the class
> thing.  Without passing the object thing to all the function calls in one
> and two (which would turn out really really messy) how can they access it?

It might be better to make have a separate module, call it "singleton.py"
or something like that, to hold your single class instance.


>   Hmm...just a sec, if thing.py initialised it's own instance of thing,
> at the global level, then could one.py and two.py do an 'import thing'
> and access it with thing.thing?

Yes!  That's how we'd access objects in other modules.  Python's modules
work really well as containers of variable names.  And since modules are
cached and loaded only once, we're guaranteed that that instance will be
instantiated only once.


The reason I think it might be better to pull your instance out into a
separate module is because 'main' is already importing the 'one' and 'two'
modules.  If 'one' or 'two' were to import 'main' as well, there'd be a
circularity.

Python often can handle import circularities usually, but it's still
confusing!  We should avoid them just to keep our brains from getting
dizzy.

Hope this helps!