[Tutor] Accessing Variables

paul brian paul1brian at gmail.com
Wed Oct 5 23:51:43 CEST 2005


Sort of....not really

When a module is imported the following things happen

import ONE

a module object (dict essentially) named ONE is created. This is the
module ONE.py's namespace.
The module object is added to sys.modules
the code in the object is executed inside the ONE dict (namespace)

now if ONE has at the top
import os

ONE is able to use the line
os.path.join (mydir, "foo.txt")

If however we do not have the line import os we will get an error
as the namespace of one does not have a reference to the module object of os

as an example import your one.py and run

pprint.pprint(sys.modules['one'].__dict__)

You will see what a virgin namesapce looks like
- there is a lot in there but it boils down to
__builtins__, __doc__, __file__, __name__ and whatever you define (_-dict__)

care notes
---------------
You can easily get into circular references with imports, simply
because code at the module level (ie not in a function or class) will
be executed at the first import - and if it calls code that is in the
next module which waits on code in the first etc etc.

So as you said, put everything into classes or functions or be very
careful with your imports.

(I am not sure I answered the question but it is late now...:-)

yrs



On 10/5/05, Matt Williams <matthew.williams at cancer.org.uk> wrote:
> Dear List,
>
> I'm trying to clarify something about accessing variables.
>
> 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).
>
> 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.
>
> Matt
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


--
--------------------------
Paul Brian
m. 07875 074 534
t. 0208 352 1741


More information about the Tutor mailing list