Create a Python Package
As a means to ensure some level of security - so that Python modules cannot access areas where they are not welcome - importing from parents or grandparents is generally prohibited... unless you create a package.
Luckily, in Python, creating a package is crazy-easy. You simply need to add a __init__.py
file in each folder/directory that you want to treat as part of the package. And, the __init__.py
file doesn't even need to contain anything. You just need the (potentially empty) file to exist.
For instance:
#current.py
from folder1.grandparent import display
display()
#grandparent.py
def display():
print("grandparent")
# ├── folder1
# │ ├── __init__.py
# │ ├── folder2
# │ │ ├── __init__.py
# │ │ └── folder3
# │ │ ├── __init__.py
# │ │ └── current.py
# │ └── grandparent.py
Next Steps
This is not in the OP's question, but highly related and worth mentioning: If you import a directory instead of a module (file), then you are importing the __init__.py
file. E.g.,
import folder1
actually performs an import of the __init__.py
file in the folder1
directory.
Lastly, the double-underscore is used so often, it's shortened to dunder. So when speaking, you can say "dunder init" to refer to __init__.py
.