Friday 29 October 2021

How to import a function in one module to a module in a different folder?

Imagine a package with this structure:

└── main_package
    ├── __init__.py
    ├── subpackage1
    │   ├── __init__.py
    │   └── module1.py
    └── subpackage2
        ├── __init__.py
        └── module2.py

What is the best way of importing a function in module1 to module2?

Should the __init__.py files contain something?

The best solution I have found is to include in module2

import sys
sys.path.append('./')
from main_package.subpackage1.module1 import fun1

And when running module2 from the directory in which main_package is it works.

But I feel like this does not take advantage of the fact that they are packages. And also it would be nice to be able to run this from wherever I want if possible.



from How to import a function in one module to a module in a different folder?

No comments:

Post a Comment