Question about imports and packages

Steven D'Aprano steve at pearwood.info
Tue May 24 21:02:41 EDT 2016


On Wed, 25 May 2016 09:35 am, Gerald Britton wrote:

For brevity, here's your package setup:


testpkg/
+-- __init__.py
+-- testimport.py which runs "from testpkg.testimported import A"
+-- testimported.py containing class A

Your package layout is correct. But:

> When I run
> 
> python testimport.py
> 
> I get:
> 
> Traceback (most recent call last):
> File "testimport.py", line 1, in <module>
> from testpkg.testimported import A
> ImportError: No module named testpkg.testimported

The problem is that you are running the Python script from *inside* the
package. That means, as far as the script can see, there is no longer a
package visible -- it cannot see its own outside from the inside.

cd to a directory *outside* the package, and run:

python testpkg/testimport.py

and it should work. Better: make sure the testpkg directory is somewhere in
your PYTHONPATH, and run:

python -m testpkg.testimport


which tells Python to search for the package, rather than using a hard-coded
path.


The package directory has to be visible to the import system. That means it
must be INSIDE one of the locations Python searches for modules. The
current directory will do, but to be absolutely clear, that means that the
package directory itself must be IN the current directory:


./
+-- pkgtest/
    +-- __init__.py
    +-- testimport.py
    +-- testimported.py


Or you can use any other directory found in sys.path.



-- 
Steven




More information about the Python-list mailing list