Re: Relative Imports, why the hell is it so hard?



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 )


.



Relevant Pages

  • Re: Insane import behaviour and regrtest.py: heeelp
    ... Python doesn't appear to look in Lib/test to ... # prevents relative imports from working, ... # much of the testing framework relies on the globals in the ...
    (comp.lang.python)
  • Problems with relative imports and pep 366
    ... I have a "canonical file structure" like that (I'm giving sensible names ... want to access the helpers utilities through relative imports in ... $ python mainpack ...
    (comp.lang.python)
  • Re: Problems with relative imports and pep 366
    ... I have a "canonical file structure" like that (I'm giving sensible names ... want to access the helpers utilities through relative imports in ... $ python mainpack ...
    (comp.lang.python)
  • Re: importing a module from a specific directory
    ... But, if you are using Python 2.5, you are saved. ... in addition to the implicit relative imports ... you can write explicit relative imports with the from module ... From the surround module for example, ...
    (comp.lang.python)
  • Re: Relative Imports, why the hell is it so hard?
    ... On Mon, Mar 23, 2009 at 10:16 AM, CinnamonDonkey ... I'm fairly new to Python so I still have a lot to learn. ... to know how to correectly use relative imports. ... Module1 needs to access functionality in Module2. ...
    (comp.lang.python)