1

Consider the following directory structure:

project/ 
    scripts/
        a1.py
        a2.py
    start.py

start.py depends on a1.py and a1.py in turn uses a function called some_func which is present in a2.py. Moreover, a1.py is also a standalone script and can be called independently. Now this gives rise two cases:

Case 1: (Standalone script) I would import some_func as follows

from a2 import some_func

Case 2: (Called from start.py)

from scripts.a2 import some_func

My Question: What is the pythonic way of combining the two use cases?

Possible Solution?: Is this recommended or not?

if __name__ == "__main__":
    from a2 import some_func
elif __name__ == "start":
    from scripts.a2 import some_func

Note: I am using python 3.x

shahensha
  • 2,051
  • 4
  • 29
  • 41
  • What is the problem with calling `from a2 import some_func` in `a1` and `from a1 import some_func` in `start`? – gosuto Dec 24 '18 at 10:44
  • You can use relative imports in a1.py, more about relative imports [here](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – Konrad Dec 24 '18 at 10:44

1 Answers1

1

Pythonic way is create a package from your code and then use intra-package references in your code: https://docs.python.org/3/tutorial/modules.html

from . import some_func  # from scripts in same folder
from .scripts import some_func  # from start.py

Also you will be able to use absolute paths (from package name) after packaging your solution and installing it, like:

# this will work from anywhere
from mypackage.scripts import some_func
grapes
  • 8,185
  • 1
  • 19
  • 31