Re: Relative Imports, why the hell is it so hard?
- From: Istvan Albert <istvan.albert@xxxxxxxxx>
- Date: Tue, 24 Mar 2009 08:49:08 -0700 (PDT)
On Mar 23, 10:16 am, CinnamonDonkey <CinnamonDon...@xxxxxxxxxxxxxx>
wrote:
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
pathfix.py 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 )
.
- Follow-Ups:
- Re: Relative Imports, why the hell is it so hard?
- From: Gabriel Genellina
- Re: Relative Imports, why the hell is it so hard?
- References:
- Relative Imports, why the hell is it so hard?
- From: CinnamonDonkey
- Relative Imports, why the hell is it so hard?
- Prev by Date: Appending to sys.path
- Next by Date: Re: install pyPgSQL on Windows for python 2.5
- Previous by thread: Re: Relative Imports, why the hell is it so hard?
- Next by thread: Re: Relative Imports, why the hell is it so hard?
- Index(es):
Relevant Pages
|