Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a Python module from a sibling folder?

I have gone through many Python relative import questions but I can't understand the issue/get it to work.

My directory structure is:

Driver.py  A/       Account.py       __init__.py  B/       Test.py       __init__.py 

Driver.py

from B import Test 

Account.py

class Account: def __init__(self):     self.money = 0 

Test.py

from ..A import Account 

When I try to run:

python Driver.py 

I get the error

Traceback (most recent call last):  from B import Test  File "B/Test.py", line 1, in <module> from ..A import Account  ValueError: Attempted relative import beyond toplevel package 
like image 651
Joshua Avatar asked Feb 14 '13 23:02

Joshua


People also ask

How does Python import modules from some other directory?

We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.

How do I import a specific module in Python?

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.

Can import Python file from same directory?

Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory". The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation.

How do I import a module from the outside directory?

Method 1: Using sys. The sys. path variable of the module sys contains the list of all directories in which python will search for a module to import. We can directly call this method to see the directories it contains. So for importing mod.py in main.py we will append the path of mod.py in sys.


2 Answers

This is happening because A and B are independent, unrelated, packages as far as Python is concerned.

Create a __init__.py in the same directory as Driver.py and everything should work as expected.

like image 91
David Wolever Avatar answered Sep 27 '22 19:09

David Wolever


In my case adding __init__.py was not enough. You also have to append the path of the parent directory if you get module not found error.

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

To import B.py from A.py, you have to do the following

import sys    # append the path of the parent directory sys.path.append("..")  from SiblingB import B print("B is successfully imported!") 
like image 21
Shekhar Avatar answered Sep 27 '22 20:09

Shekhar