Jshee
Jshee

Reputation: 2686

import class from another directory

I have:

script1.py in database/table_inserts/  #trying to import below file into
dbcrud.py in database/                 #trying to import by above file

in script1.py I have:

from ..dbcrud import set_db_setting

but this throws error:

   from ..dbcrud import set_db_setting
SystemError: Parent module '' not loaded, cannot perform relative import

What am i doing wrong?

Upvotes: 1

Views: 10797

Answers (1)

Chiheb Nexus
Chiheb Nexus

Reputation: 9257

Edit:

Thanks to @Mad Physicist comments.

The most easy and trivial way to solve your question is to add an empty __init__.py file in database/ folder and another empty __init__.py file to database/table_inserts/ folder in order to be recognized as a package.

See this example of hierarchy:

database/
├── dbcrud.py
├── __init__.py
└── table_inserts
    ├── __init__.py
    └── script1.py

1 directory, 4 files

Then all you have to do in script1.py is to import your module from dbcrud.py like this example:

# Note here the double dots '..'
from ..dbcrud import you_module

Otherwise, if you want another solution, you can edit your $PYTHONPATH variable like this way:

dbcrud.py:

class DBCrud:
    def __init__(self):
        print("I'm DBCrud'")

script1.py

# Add the parent directory to your module
# by using this kind of hack
import os, sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
# Then import your module
from dbcrud import DBCrud

class Script1:
    def __init__(self):
        print("I'm Script1'")
        DBCrud.__init__(self)

# test
if __name__ == '__main__':
    app = Script1()

Now, from database/ folder or database/table_insers/ folder you can run the test example:

~$ pwd
/user/path/database/table_inserts
~$ python3 script1.py

Output:

I'm Script1'
I'm DBCrud'

And:

~$ pwd
/user/path/database
~$ python3 table_inserts/script1.py

Output:

I'm Script1'
I'm DBCrud'

Upvotes: 7

Related Questions