Import Semantics, or 'What's the scope of an import?', and class attribute instantiation

Andrew James drew at
Sat Dec 4 15:49:53 CET 2004

I'm having some trouble with understanding python's importing behaviour
in my application. I'm using psyco to optimise part of my code, but I'm
not sure whether it inherits throughout the rest of my application (read
this as for any imported module) if I import in in a 'higher-level'
module. For example:

import psyco
from B import BClass
class AClass():
	b = BClass()

class BClass():

In general, I've noticed that if import X and B in and want to
reference X.* from, I need to import X again in B. Is this a hard
and fast rule, or is there a way I can import the common libs, etc. in
the starting .py file and have those inherited by other classes I
import/instantiate? How would I do this?

It seems to be the general consensus that it's best to keep a Python app
in fewer files in the same directory rather than spreading them out, a
few (or one) classes to a file in a directory hierarchy as in Java. I
understand this is due to Python's, self.* and import <path> operations
having a relatively high cost (traversing directories, etc. etc.)

What I don't see mentioned is that when I step through a Python script
(say, in Eric3), if the structure of the file is like this:

class myX():
	att1 = 'Test'
	att2 = []
	att3 = MemoryHungryClass()

class myY():
	a = 'Another test'


if __name__ == 'main':
	x = myX()

Python loads all the class attributes into memory (or, at least, cycles
through them) at runtime *even if I never instantiate the class*. This
has lead me to write code like:

class myX():
	att3 = None
	def __init__(self):
	att3 = MemoryHungryClass()

Which seems to work a little better, but it seems rather ugly. I guess
the reason Python does this is because it's interpreted, not statically
compiled (and so needs to know whether myX.attr3 exists when called),
but I don't understand why the interpreter can't parse/instantiate the
attributes on the first call to instantiate the class. Surely this would
be a reason *for* splitting your code up into multiple files?

Being relatively new to Python, I'm trying to avoid coding things in an
un-Python (read C++/Java) manner, and am looking for some tutorials on
python-specific advanced features I can use (things like closures,
lambda forms, map(), etc. etc.). Could anyone point me towards some good

I would much appreciate some assistance in finding some answers to these
questions, as the research I've done seems to be inconclusive, if not
downright confusing.

Many thanks,

Andrew James <drew at>

More information about the Python-list mailing list