Search code examples
python-3.xsetuptoolspython-module

Python module not recognizing files in the same folder


I've made (at least tried) a package using setuptools and attempted to use it from another python-file. However, the modules within the packages don't seem to recognize each other.

Tree

pkg
|-- pkg
|     |-- __init__.py
|     \-- module.py
\-- setup.py

__init__.py:

import module
#code

pyfile.py

import pkg
#code

When I attempt to run pyfile.py, I get

Traceback (most recent call last):
  File "/.../py/pyfile.py", line 1, in <module>
    import pkg
  File "/.../pkg/pkg/__init__.py", line 1, in <module>
    import module
  ModuleNotFoundError: No module named 'module'

It works fine if I write import pkg.module, but I don't see why self.referential code would be practical.


Solution

  • Change the import in your __init__ to

    from . import module
    

    You can read more about intra-package references in the python documentation.

    (BTW, as far as I can tell, setuptools is not involved here.)