0

my_module.py is a file in a package I'm developing. Sometimes I want to run it on its own (python -i my_module.py) for debugging purposes.

from .other_module import x, y-syntax relative imports fail in the case of running it directly.

I've worked around the problem by filling the top of every file in my package with these kinds of statements instead of normal imports:

try:
    from .other_module import x, y
except ImportError:
    from other_module import x, y

but now I have the ugliest preamble I've ever seen.

How is this kind of problem meant to be resolved? I just want to import relative modules no matter whether I am currently being run as a module in a package, or being run for debugging purposes on my own.

theonlygusti
  • 11,032
  • 11
  • 64
  • 119
  • Run the module as a script instead, using the `-m` flag, per the advice at the linked duplicate. Then relative imports will work, because the module is still recognized as part of its package. In this case, `python -im my_module`. – Karl Knechtel Jan 19 '23 at 08:59

1 Answers1

0

It may be sufficient to set PYTHONPATH when running so imports are always relative to the project root

PYTHONPATH=$HOME/code/package/src/package python3 src/package/foo.py
ti7
  • 16,375
  • 6
  • 40
  • 68