Python import not working, even after creating __init__ in parent folders

32 Views Asked by At

Why isn't this import statement working, even after I created __init__ in every folder?

Import not working in Python

I want to import func1() from basepackage\package1\p1\p1py.py. The root folder basepackage is located on my desktop.

import package1.p1.p1py
import basepackage.package1.p1.pipy as okay     '''this king of import statement is showing error'''
okay.func1()
package1.p1.p1py.func1()  

The code above doesn't work, and throws the following error:

File "c:\Users\shiv\Desktop\basepackage\package1\p11\p11py.py", line 1, in <module>
import package1.p1.p1py
ModuleNotFoundError: No module named 'package1'
1

There are 1 best solutions below

0
Matt Pitkin On

Within the package you need to use relative imports rather than importing from the package name itself (that will only work if the package is already installed in your Python path).

For example, if I have a package set up like:

base
.
└── package1
    ├── __init__.py
    ├── p1
    │   ├── __init__.py
    │   └── p1py.py
    └── p11
        ├── __init__.py
        └── p11py.py

and p1py.py contains:

def func1():
    print("Hello!")

Then, if you wanted p11py.py to be able to use func1, then you could have it contain:

# relative import from p1.p1py
from ..p1.p1py import func1

def func2():
    # use func1!
    func1()

Then, within the base directory, you can do:

from package1.p11.p11py import func2

func2()
Hello!

See, e.g., Relative imports for the billionth time for links to various other questions/answers about relative imports.