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
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.
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.
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.
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.
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.
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!")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With