Force importing module from current directory

Question:

I have package p that has modules a and b. a relies on b:

b.py contents:

import a

However I want to ensure that b imports my a module from the same p package directory and not just any a module from PYTHONPATH.

So I’m trying to change b.py like the following:

from . import a

This works as long as I import b when I’m outside of p package directory. Given the following files:

/tmp
    /p
       a.py
       b.py
       __init__.py

The following works:

$ cd /tmp
$ echo 'import p.b' | python

The following does NOT work:

$ cd /tmp/p
$ echo 'import b' | python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "b.py", line 1, in <module>
    from . import a
ValueError: Attempted relative import in non-package

Why?

P.S. I’m using Python 2.7.3

Asked By: Zaar Hai

||

Answers:

Because there is an __init__.py file in /p. This file tells Python: “All modules in this folder are in the package p“.

As long as the __init__.py file exists, you can import b as p.b, no matter where you are.

So the correct import in b.py would be: import p.a

Answered By: Aaron Digulla

Relative imports only work within packages.

If you import b from where you are, there is no notion of a package, and thus there is no way for a relative import.

If you import p.b, it is module b within package c.

It is not the directory structure which matters, but the packages structure.

Answered By: glglgl

After rereading the Python import documentation, the correct answer to my original problem is:

To ensure that b imports a from its own package its just enough to write the following in the b:

import a

Here is the quote from the docs:

The submodules often need to refer to each other. For example, the
surround module might use the echo module. In fact, such references
are so common that the import statement first looks in the containing
package before looking in the standard module search path.

Note: As J.F. Sebastian suggest in the comment below, use of implicit imports is not advised, and they are, in fact, gone in Python 3.

Answered By: Zaar Hai
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.