Richard Lamboj wrote:
Am Friday 07 May 2010 13:50:15 schrieb Jean-Michel Pichavant:
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

Hello,

I always use absolute imports, but sometimes i does not work.

I got: ImportError: No module named mail. When i import it from top of the module it works. If i import it from a level down, it works not always - strange?

Kind Regards,

Richi
Absolute imports works, 100%. You're doing something wrong.

"No module named mail" means you forgot to prefix your submodule mail by the package name. It should be something like

import pkg.mail

The rule is simple, if pkg is your package, any import of a submodule should start with import pkg. Also note that your package must be properly installed (i.e. import pkg should work, no matter the directory you're in). If you don't want to install your package (don't wanna mess your PYTHONPATH with dev package), then you have to run your scripts from pkg/..


JM
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to