Home > Back-end >  How can I import a python class which is in a sub directory, where the script and sub directory both
How can I import a python class which is in a sub directory, where the script and sub directory both

Time:10-01

Given below is my folder structure.

Main_Folder
|
|-my_script.py
|
|-level-1
    |--__init__.py
    |
    |--level-2
        |--__init__.py
        |
        |--new_script.py

The new script is a small code snippet

class check:
    def print_me():
        print("inside the class")

I am trying to import this inside my_script.py. The code snippet is:

import importlib

mod = importlib.import_module("level-1.level-2.new_script.check")

my_instance = check()

my_instance.print_me()

I am getting the following error:

Traceback (most recent call last):
  File "/home/danish/tuts/del_check/my_script.py", line 4, in <module>
    mod = importlib.import_module("level-1.level-2.new_script.check")
  File "/home/danish/anaconda3/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 970, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'level-1.level-2.new_script.check'; 'level-1.level-2.new_script' is not a package

I went ahead and searched following solution . But no use. What am I doing wrong here. Also, changing the directory name is not an option.

CodePudding user response:

Let's first update your class method:

class check:
    def print_me(self):
        print("inside the class")

Then we can import the module. Note, check is a class so let's not try to import it as a module.

import importlib
mod = importlib.import_module("level-1.level-2.new_script")
my_instance = mod.check()
my_instance.print_me()

This should give you:

inside the class
  • Related