-1

I am new to python. I have a project with the structure as described below and I just want to use functions from one module into another across the package1 and package2 directories. Can I use functions from module3.py in module1.py just by using the import statement (similar as in java or C#)

# in package1.module1.py
from package2 import module3.py 

without any package installation (e.g. locally with 'pip install -e .') and setup.py configuration?

Here an example project structure

└── project
    ├── package1
    │   ├── module1.py  <- I want that this module uses functions from module3.py 
    │   └── module2.py
    └── package2
        ├── __init__.py
        ├── module3.py
        ├── module4.py
        └── subpackage1
            └── module5.py
anar chipur
  • 109
  • 2
  • 10

1 Answers1

0

Yes, that should work, and you don't need an __init__.py unless you want to import the package itself, i.e.

import package2

The key thing though, is that 'project' needs to be in your PYTHONPATH. You will not notice that if you run python interactively, because I believe it automatically adds the current directory to the PYTHONPATH.

in practice you'd do

from package2 import module3   # notice, no .py
module3.somefn()
joelhoro
  • 890
  • 1
  • 9
  • 20
  • 1
    `PYTHONPATH` is almost never good practice because it will not scale beyond a couple packages before it becomes impractical to manage. It is always better to build real packages that may be installed into any Python environment. – metatoaster Jul 05 '20 at 01:56
  • Could be, but the OP asked for a solution that does not require packages. – joelhoro Jul 05 '20 at 04:15