A script or module can import modules that either
- on the system path or
- part of the same package as the importing script / module.
For modules, these rules apply without exception. Rules apply for scripts, but the wrinkle is that by default when you run the script it is not considered part of the package.
This means that by default, a script can only import modules that are in the system path. By default, the path includes the current directory, so if you run the script, it can import the modules in the same directory or in packages that are subdirectories. But it is so. A script does not have the concept of โwhere is itโ in the directory tree, so it cannot do imports that require certain relative information about the path to the subdirectories. This means that you cannot import things "from the parent directory" or "from the directory for sisters." Things that are in these directories can only be imported if they are on the way to the system.
If you want to make the script "know" that is in the package, you can assign the __package__ attribute to __package__ . See this previous question . Then you can use explicitly relative imports (e.g. from ...sub2 import mod2 ) from within the script.
source share