Python Relative import from parent directory when current script needs to run a main file

255 Views Asked by At

I am working on a code where we have the following directory structure

base dir
|
--J
| |--C
| |  |--H
| |  |  |--M_task.py
| |  |
| |  |--C_task.py
| |  |
| |  |--A_task.py
|

All folders are packages.
I have two requirements:

  1. I need to be able to import M_task module in A_task.
    That I am able to achieve using
    from H.M_task import method
  2. import C_task inside M_task

In the second case I am facing several problems.
I can use absolute import when I am running the code on my local machine but it will not be possible to use absolute import when the code is deployed. So it is out of question.
Using from ..C_task import method works only if I am using M_task only as a module. But I need to run M_task as script using main function in some cases. In that case, M_task does not have a parent folder and hence relative import does not work.
Last resort is appending parent folder to sys.path. But I want to avoid that solution as much as possible. Is there a cleaner way available to achieve what I want to here?

1

There are 1 best solutions below

0
On

The correct way of running whatever you want is from base dir - so

$ cd "/path/to/base dir"
$ python -m J.C.H.M_task

The -m switch does the package detection magic - note you omit the py extension. It is an anti-pattern to run directly from the module dir cause of all the problems you faced.