Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force importing module from current directory

Tags:

python

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

like image 702
Zaar Hai Avatar asked Jan 08 '13 13:01

Zaar Hai


People also ask

How do I import a module into a different folder?

The most Pythonic way to import a module from another folder is to place an empty file named __init__.py into that folder and use the relative path with the dot notation. For example, a module in the parent folder would be imported with from .. import module .

How do I run a Python module from another directory?

We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.

How do I manually import a Python module?

append() Function. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.


1 Answers

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.

like image 120
Zaar Hai Avatar answered Oct 04 '22 09:10

Zaar Hai