kubernetespython-modulepython-3.12relative-import

Python 3 relative imports behave differently between local run and on k8s


I have the following structure:

project/
  |- src/
       |- __init__.py
       |- package/
             |- __init__.py
             |- module1.py
             |- module2.py

Let's say module1.py tries to import a symbol from module2:

from .module2 import MySymbol

Run it locally with python <filename>.py and this hits the error: ImportError: attempted relative import with no known parent package whether I run it from project or from project/src/package. I try:

from src.package.module2 import MySymbol

and it complains no module named src...

When it runs in a k8s cluster, it hits the error without a . prefix:

ModuleNotFoundError: No module named 'module1'

This is a dilemma for me because importing local module in the same folder using . prefix works when the app runs in k8s pod. However, this doesn't run locally. How to get the best of these 2 worlds?


Solution

  • You should be running your script from the project folder - as in:

    $ cd /path/to/project
    $ python -m src.package.module1 # or whatever filename is but *without* the .py
    

    Then both absolute and relative import forms will work.