Module not detected in python3 but works in python2

Viewed 1804

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
2 Answers

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.

Whether you had helper.py in your python path would determine if you are able to import it directly or not.

And if you did not explicitly set PYTHONPATH, the directory from where you tried to run your script would get added to the PYTHONPATH.

Addendum:

If we are trying import something with a relative import:

from .module import data

is adviced.

However, it is always better to provide the full path like this:

from pkg_name.helper import MyClass

to avoid any ambiguity.

Related