I am following the easy guide on the Python Central to create a package for my code:
https://www.pythoncentral.io/how-to-create-a-python-package/
So my directory structure is:
main.py
pack1/
__init__.py
Class1.py
In the main.py
file I import and use Class1
as:
from pack1 import Class1
var1 = Class1()
In the __init__.py
file I have written:
import Class1 from Class1
I followed the guide exactly and still get the error:
ModuleNotFoundError: No module named 'Class1' (in __init__.py)
Python 3 has absolute imports. Change your __init__.py
to :
from .Class1 import Class1
The leading dot indicates that this module is found relative to the location of __init__.py
, here in the same directory. Otherwise, it looks for a standalone module with this name.
PEP 328 gives all details. Since Python 3.0 this is the only way:
Removed Syntax
The only acceptable syntax for relative imports is
from .[module] import name
. Allimport
forms not starting with.
are interpreted as absolute imports. (PEP 0328)
The file Class1.py
contains this code:
class Class1:
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With