0

I have a project directory as below:

bin/
bin/module1/module1.py
bin/module1/settings.py 
bin/module1/helpers.py  --> This module does not have reference to bin/module1/settings.py
bin/module2/module2.py
bin/module2/settings.py
bin/module2/helpers.py --> This module has reference to bin/module2/settings.py
bin/tests/test_module1.py --> This test imports helpers from bin/module1/helpers.py
bin/tests/test_module2.py --> This test imports helpers from bin/module2/helpers.py
bin/tox.ini
bin/conftest.py
bin/setup.py

setup.py has below contents:

from setuptools import setup, find_packages

setup(
    name='my_project',
    version='0.0.1',
    description='Implement my_project',
    long_description='Implement my_project',
    author='my_name',
    author_email='a.my_name@my_domain.com',
    packages=find_packages(exclude=['tests*'])
)

I am using pytest.

When I run test_module1.py, which refers bin/module1/helpers.py using pytest markers and bin/module1/helpers.py does not have import to bin/module1/settings.py. The test run perfectly fine.

But, when I run bin/tests/test_module2.py using pytest markers, and bin/module2/helpers.py has import to bin/module2/settings.py, when this test runs I see the ModuleNotFoundError: No module named 'settings' error

    import settings as settings
E   ModuleNotFoundError: No module named 'settings'
Shankar Guru
  • 1,071
  • 2
  • 26
  • 46

2 Answers2

0

The only method i know is to change
import settings as settings
to
import .settings as settings Happy coding!

Dharman
  • 30,962
  • 25
  • 85
  • 135
Aryasatya
  • 36
  • 1
  • 3
  • Thank you, but `import .settings as settings` throws error. So, I changed to `from .settings import *` it worked. This works fine when running as test i.e. `bin/tests/test_module2.py` But, when I run python module `bin/module2/module2.py` I get `ImportError: attempted relative import with no known parent package` – Shankar Guru Aug 05 '20 at 12:57
0

The issue was resolved using SO link: Getting "ImportError: attempted relative import with no known parent package" when running from Python Interpreter

Used Approach 1 from above link which is as below:

try:
    # Assume we're a sub-module in a package.
    from . import models
except ImportError:
    # Apparently no higher-level package has been imported, fall back to a local import.
    import models
Shankar Guru
  • 1,071
  • 2
  • 26
  • 46