From: Jean-Michel Pichavant on 7 May 2010 08:43
Richard Lamboj wrote:
> Am Friday 07 May 2010 13:50:15 schrieb Jean-Michel Pichavant:
>> Richard Lamboj wrote:
>>> 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,
>> 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.
> 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 -
> Kind Regards,
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
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/..
First | Prev |
Pages: 1 2
Prev: ActivePython - how to configure portable framework?
Next: listing exported functions in a DLL