[Tutor] Accessing Variables

Alan Gauld alan.gauld at freenet.co.uk
Thu Oct 6 01:08:25 CEST 2005


> If I have ONE.py file with some variable a, and ONE imports TWO, which
> has a variable b, can TWO access variable a (I don't think so, but I
> just thought I'd check).

Correct you can't do it. And quite rightly so because trying to do so would
indicate a faulty design! When we import a module it can be one of two 
things:
1) A generic reusable bit of code written by someone else which has no
    knowledge of the internal structure of our code, therefore it can never
   attempt to access our code.
2) A module that we have written as part of an overall solution. If that
    module tries to access code in our module it means we have not factored
    our code properly to produce reusable modules(in fact the moduile is
    not modular!

Modules should only access their own data or the data in other modules
that they import, there should not be cyclic dependencies. If there are,
we have a faulty design.

> I guess the way round this is just to make some classes & objects, and
> then they can easily pass parameters to each other, but I just thought
> I'd check.

You can pass parameters between modules without resorting to classes,
thats an entirely different animal;

###### ONE.py #####

import TWO

onevar = TWO.twovar

TWO.init(onevar)
TWO.foo()

######## TWO.py ####

class UninitialisedModuleError(Exception)

twovar = 77
importer = None  #placeholder variable

def init(aValue):
    global onevar
    onevar = aValue

def foo():
   if onevar:
       print onevar
   else:
        raise UninitialisedModuleError

#############

So by using an init function TWO can grab a value from whatever
module imports TWO. If the module is not initialised an exception
gets raised. This mechanism provides a safe way to avoid circular
dependencies by keeping TWO ignorant of the innards of the
importing module.

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list