importing modules

Jean-Michel Pichavant jeanmichel at sequans.com
Fri May 7 07:50:15 EDT 2010


Richard Lamboj wrote:
> Hello,
>
> I have a question about importing python modules.
>
> I have modul package, with submodules. So how can a  submodul access a modul 
> that is on level upper?
>
> Is there something like "import ../../blah"? I don't mean something like 
> this: "import bla.blub.moep"
>
> Kind Regards,
>
> Richi
>   
I would advise to use absolute imports whenever possible (always ?).
If 'pkg' is your package, then module sub1 should import sub2 that way:

file pkg/sub1.py:

import pkg.sub2


see http://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports

" the python-dev community chose absolute imports as the default because 
they're the more common use case and because absolute imports can 
provide all the functionality of relative (intra-package) imports -- 
albeit at the cost of difficulty when renaming package pieces higher up 
in the hierarchy or when moving one package inside another."

You can still use relative import if you want, they've been implemented 
for a purpose, but I woudl highly discourage the ambiguous relative 
imports of python 2.4.

JM





More information about the Python-list mailing list