relative imports improve program organization... suggestions?

castironpi castironpi at gmail.com
Sat Aug 9 06:33:56 CEST 2008


On Aug 8, 12:37 pm, DG <dang... at gmail.com> wrote:
> Alright, I have searched and searched and read many conversations on
> the topic of relative and absolute imports and am still not getting
> the whole thing through my skull.
>
> Highlights of what I've read:http://mail.python.org/pipermail/python-list/2007-January/422973.htmlhttp://groups.google.com/group/comp.lang.python/browse_thread/thread/...http://www.python.org/dev/peps/pep-0328/http://docs.python.org/whatsnew/pep-328.html
>
> So my problem and argument:
> I want to create a package organized as the following:
> pckg/
>      __init__.py
>      main.py
>      moduleA/
>           __init__.py
>           A_base.py
>           A1/
>                __init__.py
>                A_inherit1.py
>                other_A1_files...
>           A2/
>                __init__.py
>                A_inherit2.py
>                other_A2_files...
>      moduleB/
>           ...
> Explanation:
> The main program is located in main.py and it implements the different
> modules (A, B).  Within the modules the basic organization is; the
> base class for all different types of A is directly within the moduleA
> directory.  All of the different inherited classes of A are within
> their own subdirectory with a mess of their own files.  This is done
> so that a new subclass of A can be added/removed by just adding/
> removing the subdirectory and each of these subclasses may have their
> own maintainer, but they should all inherit from A_base.py
>
> If I am developing the A1 directory, I want to be able to test
> A_inherit1.py by using 'if __name__ == "__main__"' within the
> A_inherit1.py file and by typing 'python A_inherit1.py' on the command
> line.  I prefer this simply to keep all unit tests within the same
> directory and same file as the inherited class.
>
> My Problem:
> A_inherit1.py has the line:
>      'from ..A_base import A_Base_Class'
> so that I can later declare the inherited class as such:
>      'A1_Inherited_Class(A_Base_Class):'
>
> *BUT* I get the 'attempted relative import in non-package' error even
> when I try the
> 'from __future__ import absolute_import' command.
> I would prefer to be able to test the file without adding anything to
> the PYTHONPATH, like I said by using the name == main trick.
>
> So could someone explain to me what the rationale behind not allowing
> parent directory relative imports is?  And possibly what I can do to
> get around it?  (I really don't like messing with the sys.path for
> something like this)
>
> Thanks,
> Danny G

Didn't read the whole thing, but would imp.load_source( name,
relative_path ) help you at all?



More information about the Python-list mailing list