Search code examples
python-3.xclassoopmodulesubdirectory

how to import function from sub directory in Python3


I have a project with below structure:

enter image description here

TestDir.init.py contains:

from . import TestSubDirFile

TestDir.TestSubDirFile.py contains:

class TestSubDirFile:
def test_funct(self):
    print("Hello World")

ds_scheduler.py contains:

from TestDir import TestSubDirFile as tp

def test_job():
    testobj = tp.test_funct()
    print("Test job executed.")

if __name__ == "__main__":
     test_job()

Getting Output as:

Traceback (most recent call last):
 File "C:/Python_Projects/Test/com/xyz/ds/ds_schedular.py", line 9, in <module>
test_job()
 File "C:/Python_Projects/Test/com/xyz/ds/ds_schedular.py", line 5, in test_job
testobj = tp.test_funct()
AttributeError: module 'TestDir.TestSubDirFile' has no attribute 'test_funct'

Solution

  • As per your directory structure

    ds_scheduler.py
    TestDir -- Directory Name
    - TestSubDirFile.py - Python filename

    Within TestSubDirFile.py file you have defined your class with name TestSubDirFile.

    from TestDir import TestSubDirFile as tp

    As per your above import statement you are only accessing till the py file.

    To access test_func() method within class you need to follow below steps.

    tsdf = tp.TestSubDirFile() tsdf.test_funct()

    Hope this helps