SuperCiocia
SuperCiocia

Reputation: 1971

Python - imports and folder structure

I have the following file structure:

command.py
simulations
  basis
    basis.py
  hamiltonian
    hamiltonian.py

where the names without extensions are folders.

from basis.basis import Basis

from hamiltonian.hamiltonian import Hamiltonian

where Basis and Hamiltonian are two classes.

I can run command.py fine, all the imports are Okay.

--

1) Can I somehow run the os.chdir('..') only if hamiltonian.py is run on its own? Like with if name == 'main'?

2) Is there a more elegant solution to this?

Upvotes: 0

Views: 90

Answers (1)

Ghasem Naddaf
Ghasem Naddaf

Reputation: 862

1) You can, but its not a good idea. It is better to avoid using os.chdir.

2) The fact that you need os.chdir suggests that you are trying to run it locally like:

python ./simulations/hamiltonian/hamiltonian.py

If this is the case, use:

PYTHONPATH=. python ./simulations/hamiltonian/hamiltonian.py

You will not run into this problem if you properly install the python package and your package has the proper __init__.py files as suggested by @E.Serra.

Upvotes: 1

Related Questions