0
├── apps
│   ├── package1
│   ├── directory 1
│   │   ├── demo1.py
│   │   └── demo2.py
└   └── test1.py
└   └── test2.py (def function2)

here i need to access function2 in test2.py, and use it in demo2.py

it will look like in demo.py file as below

from test2 import function2 

and got an following error ImportError: cannot import name 'function2' from 'test2'

davidism
  • 121,510
  • 29
  • 395
  • 339
Sri hari
  • 9
  • 3

1 Answers1

0

What I have done in situations where I am facing import issues like that. I use sys module and append the directory that contains the package I need to import (test2.py in your case) to the paths that python will check when looking for files as you try to import.

So something like that

import sys
path_to_project = '/path/to/project/apps/'
if path_to_project not in sys.path:
   sys.path.append(path_to_project)

from test2 import function2
djvaroli
  • 1,223
  • 1
  • 11
  • 28
  • tried ..test2 and got an ImportError: attempted relative import with no known parent package – Sri hari Feb 24 '21 at 15:25
  • @Srihari Yeah, sorry, I think the relative import method won't work here, the first one worked for me when I tried it though. – djvaroli Feb 24 '21 at 15:26
  • bro can you kindly explain the 1st one related with my example.... kindly use my example keywords and recreate your 1st answer with my example – Sri hari Feb 25 '21 at 07:15