Running modules inside a package as executable files is bad practice.
When you develop something, you either create a library that is intended to be imported by other programs, and therefore it makes no sense to allow the direct execution of your submodules or you create an executable file, in which case there is no reason to make it part of the package.
This is why in setup.py you distinguish between packages and scripts. Packages will be under site-packages , while scripts will be installed under /usr/bin (or a similar location depending on the OS).
My recommendation, therefore, should use the following layout:
/ βββ mydirectory | βββ __init__.py | βββ file1.py βββ file2.py
Where file2.py imports file1.py like any other code that wants to use the mydirectory library, with absolute import:
from mydirectory.file1 import f
When you write setup.py script for the project, you simply list mydirectory as a package and file2.py as a script, and everything will work. No need to mess with sys.path .
If you ever, for some reason, really want to run a package submodule, the correct way to do this is to use the -m switch:
python -m mydirectory.file1
Loads the entire package and then executes the module as a script, allowing relative imports to succeed.
I would personally avoid this. Also, because many people do not even know that you can do this, and in the end you will get the same error as you, and think that the package is broken.
Regarding the currently accepted answer, which says that you should use implicit relative imports from file1 import f , because it will work because they are in the same directory:
This is wrong !
- It will not work in python3, where implicit relative imports will be prohibited and will certainly break if you install the
file1 module (since it will be imported instead of your module!). Even if it works, file1 will not be considered as part of the mydirectory package. It can make a difference.
For example, if file1 uses pickle , the package name is important for the correct loading / unloading of data.