relative import packages/modules workaround

Terry Hancock hancock at
Mon Jul 11 21:18:07 CEST 2005

On Monday 11 July 2005 09:19 am, peter wrote:
> I've read all the posts concerning relative imports of modules and I am
> glad I saw some consensus on a syntax.
> At this moment I am however bound to python 2.3.
> Does anyone know a good workaround (or a library) which can achieve a
> relative import for this python version

Basically, you can use information from the sys module to dynamically
determine your module or package's absolute path.  Then you construct
the absolute path to the module you want by a fairly simple application
of os.path from the relative path. 

How exactly to do that is not something I remember off the top of my
head, but I remember it's not hard -- check the "sys" and "os.path"
modules' documentation. You probably also want to look at the 
"__path__" property of packaged loaded with, as I believe
there is some special "magic" behavior designed for packages to make
this a little easier.

You can easily encapsulate this in a function under your module with
just a few lines of code.  Zope provides a function called "package_home"
that does this. I'm sure there are other examples.

The missing thing here is not that there's no way to do it, but rather
that it's a common enough task that there ought to be *one* way to do
it and it ought to be in the library.  Otherwise, there's a lot of

Terry Hancock ( hancock at )
Anansi Spaceworks

More information about the Python-list mailing list