Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create packages in Python 3? ModuleNotFoundError

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)
like image 993
Kanerva Peter Avatar asked Jan 05 '18 14:01

Kanerva Peter


1 Answers

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. All import forms not starting with . are interpreted as absolute imports. (PEP 0328)

The file Class1.py contains this code:

class Class1:
    pass
like image 183
Mike Müller Avatar answered Oct 01 '22 17:10

Mike Müller