import function from another folder's file

3.3k Views Asked by At

My project directory looks like this:

project/
├─ new/
│  ├─ test.py
├─ docs.py
├─ main.py

Within my main.py, I import a function from docs.pylike this:

from docs import get_my_conn

and it works fine.

How can I import the same thing within new/test.py as well? I tried:

from ..docs import get_my_conn

but I get this error:

ImportError: attempted relative import with no known parent package
2

There are 2 best solutions below

2
On

The issue is in how you are running your code - you should add the init files as in

project/
├─ new/
│  ├─ test.py
   ├─ __init__.py
├─ docs.py
├─ main.py

then run your code as

python -m new.test # note no py

from the project folder.

7
On

What you need to do is initialize the new directory as a package. In order to do this, inside the new directory make an empty file titled __init__.py. After you do this, go back to your main.py code and import it like this instead:

from new.test import (function)

Your new tree should look like this:

project/
├─ new/
│  ├─ test.py
|  ├─ __init__.py
├─ docs.py
├─ main.py

P.S. If you are trying to import a function from docs.py into test.py, you probably should not do this. This is because it will result in an error known as a circular import. This will cause your script to no longer work. If you want to import a function from docs.py into test.py then put them in the same directory (or directory at the same level of the project hierarchy).