Skip to content
Advertisement

Unable to load submodules of a Python package: ModuleNotFoundError: No module named

I am new to Python. This looks like a very simple problem but I am unable to solve it after trying my best.

I am trying to publish a python package that I developed to an artifact store. However, when I download the package on a target machine, it runs into the error about inner modules not found. The packaging and installation both look good. The output messages show that it does include the submodules.

I have a directory structure as per below.

JavaScript

Below are the contents of the files. The init files are empty.

hello.py

JavaScript

dir1pkg.py

JavaScript

setup.py

JavaScript

Below is how I am packaging and publishing to artifacts repo.

JavaScript

Below is how I am installing on the target.

JavaScript

This gives me the error below

C:UsersmananDesktop>python -m samplepackage.hello.py
Traceback (most recent call last):
  File "C:UsersmananAppDataLocalProgramsPythonPython38librunpy.py", line 185, in _run_module_as_main
    mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
  File "C:UsersmananAppDataLocalProgramsPythonPython38librunpy.py", line 111, in _get_module_details
    __import__(pkg_name)
  File "C:UsersmananAppDataLocalProgramsPythonPython38libsite-packagessamplepackagehello.py", line 2, in 
    from dir1.dir1pkg import dir1pkg
ModuleNotFoundError: No module named 'dir1'

However, this runs just fine from where I am developing the package. I can execute below and it is able to find the inner module without any issues.

C:UsersmdmehtaDesktopPythonPackagesamplepackage>python hello.py
This is msg

I have tried doing a lot of twicks around setup.py but none of them work. Even the output of the installed package looks good. I do see dir1 being included as a package.

>>> help('samplepackage')
Help on package samplepackage:

NAME
    samplepackage

PACKAGE CONTENTS
    dir1 (package)
    hello

FILE
    c:usersmdmehtaappdatalocalprogramspythonpython38libsite-packagessamplepackage__init__.py

Advertisement

Answer

Figured out the problem. We have to use full imports for it to work.

The file hello.py should use from samplepackage.dir1.dir1pkg import dir1pkg

Do not use Visual studio for python projects. It does not like fully qualified package names. Switched to pycharm and modified the package imports to fully qualified ones and everything started working.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement