简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM