Friday, December 27, 2024
Google search engine
HomeLanguagesPython – Import from sibling directory

Python – Import from sibling directory

In this article, we will discuss ways to import files from the sibling directory in Python. First, create two folders in a root folder, and in each folder create a python file. Below is the dictionary tree:

Directory Tree:

root :
 |
 |__SiblingA:
 |    \__A.py
 |     
 |__SiblingB:
 |      \__B.py

In B.py we will create a simple function and in A.py we will import the sibling module and call the function created in B.py. In order to import the sibling module in A.py we need to specify the parent directory in A.py which can be done by using path.append() method in the sys module. Passing ‘..’ in append() method will append the path of the parent directory in A.py 

Code for A.py :

Python3




# import requi9red module
import sys
 
# append the path of the
# parent directory
sys.path.append("..")
 
# import method from sibling
# module
from SiblingB.B import methodB
 
# call method
s = methodB()
print(s)


Code for B.py :

Python3




# defining method to import
# in A.py which returns a string
def methodB():
    return "\n\nThis is methodB from SiblingB"


Output after execution of A.py :

A.py is executed and the methodB() is called.

Note: We cannot directly import the methodB from A.py as “from ..SiblingB.B import methodB” this will give an error stating that ImportError: attempted relative import with no known parent package. This is because python does not consider the current working directory as a package if __init__.py is not defined in it.

Another similar way of performing the same task is by making the sibling directories as a package by putting the __init__.py file in the folders and then importing it from the sibling directory. __init__.py can be made to import the required methods to the other modules. Below is the dictionary tree:

Directory Tree:

root :
 |
 |__SiblingA:
 |    \__A.py
 |     
 |__SiblingB:
 |      \_ __init__.py
 |      \__B.py
 |

Code for A.py :

Python3




# import requi9red module
import sys
 
# append the path of the
# parent directory
sys.path.append("..")
 
# import method from sibling
# module
from SiblingB import methodB
 
# call method
s = methodB()
print(s)


Code for __init__.py :

Python3




# from .fileName import methodName
from .B import methodB


Code for B.py :

Python3




# defining method to import in
# A.py which returns this string
def methodB():
    return "\n\nThis is methodB from SiblingB"


Output after execution of A.py :

NOTE: Once __init__.py is placed inside a folder this folder now acts as a package in python.

RELATED ARTICLES

Most Popular

Recent Comments