Search code examples
pythonpython-3.xpython-importimporterror

Module not detected in python3 but works in python2


I installed a python package which has below dir structure.

pkg_name/
  __init__.py
  work.py
  helper.py

In work.py, an import is done as below -

from helper import MyClass

It works fine in python2.7 virtual env but gives below error in python3 venv

ModuleNotFoundError: No module named 'helper'

I modified the work.py import statement by adding "." as below and then it works fine in python3.

from .helper import MyClass

Question - Is there a way to make it run in python3 without modifying package files? (Or the package is published keeping just python2 in mind)

EDIT: Adding __init__.py content below

from .work import Sample
from .helper import MyClass

Solution

  • I think you run out of luck. The documentation of Python 3 states:

    Relative imports use leading dots. A single leading dot indicates a relative import, starting with the current package. Two or more leading dots indicate a relative import to the parent(s) of the current package, one level per dot after the first.

    For more information about this change, see this PEP from almost 16 years ago.

    I suggest to stop using Python 2 and get used to the Python 3 way of working.