Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how can I import from a grandparent folder with a relative path?

Imagine a folder structure as follows:

project/
    grandparent.py
    folder1/
        parent.py
        folder2/
            sibling.py
            current.py

If I am in current.py I can import from the other files using relative paths as follows:

from .sibling import *
from ..parent import *

How can I import from grandparent.py ?

(I've tried ...grandparent and ../..grandparent )

like image 315
lofidevops Avatar asked Dec 20 '25 03:12

lofidevops


1 Answers

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.

like image 106
ZYYYY Avatar answered Dec 21 '25 16:12

ZYYYY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!