A script or module can import modules that are either
- on the system path, or
- part of the same package as the importing script/module.
For modules these rules apply without exception. For scripts, the rules apply, but the wrinkle is that by default when you run a script, it is not considered to be part of a package.
This means that by default a script can only import modules that are on the system path. By default the path includes the current directory, so if you run a script, it can import modules in the same directory, or packages that are subdirectories. But that's it. A script has no notion of "where it is" in the directory tree, so it can't do any imports that require specific relative path information about enclosing directories. That means you cannot import things "from the parent directory" or "from a sibling directory". Things that are in those directories can only be imported if they are on the system path.
If you want to make a script "know" that is in a package, you can give it a __package__
attribute. See this previous question. You can then use explicit relative imports (e.g., from ...sub2 import mod2
) normally from within that script.