Relative Imports, why the hell is it so hard?

Istvan Albert istvan.albert at
Tue Mar 24 16:49:08 CET 2009

On Mar 23, 10:16 am, CinnamonDonkey <CinnamonDon... at>

> I'm fairly new to Python so I still have a lot to learn. But I'd like
> to know how to correectly use relative imports.

Relative imports are *fundamentally* broken in python. You will soon
see that code using relative import will break if you attempt to run
the module on its own. Yes, it is mindboggling!

Why is it so you ask? It is one of those issue that would be trivial
to implement correctly (it is relative to the current file location,
duh!!!), would be tremendously useful yet  for some reason it is
controversial with those who would need to implement it.

It looks like they think that the expected mode of operation would
greatly confuse the 'rest' of us. So that is the reason you end up
with a broken implementation that is worse than not having it at all.
All I can do is recommend that you avoid relative imports.

The easiest way around the issue is to create a module named like the one below and import it in all of your modules.
This is the only way to fix this issue in a way that does not come
back and bite you, it is ugly, you are repeating yourself in multiple
places, but it is still better than the alternative.


import os, sys

def path_join(*args):
    return os.path.abspath(os.path.join(*args))

# adds base directory to import path to allow relative imports
__currdir = os.path.dirname( __file__ )
__basedir = path_join(__currdir, '..' )
if __basedir not in sys.path:
    sys.path.append( __basedir )

More information about the Python-list mailing list