简体   繁体   中英

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.

  • command.py is importing basis.py and hamiltonian.py like:

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.

  • Now, I want to work with hamiltonian.py alone, but it needs to import basis.py .

  • In order for command.py to work fine, the import in hamiltonian.py has to be from basis.basis import Basis

  • In order for hamiltonian.py to run on its own, the import needs to be

    os.chdir('..')
    from basis.basis import Basis
    however this makes command.py not work anymore.

--

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM