9

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)
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
Kanerva Peter
  • 237
  • 5
  • 13

1 Answers1

12

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
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • Okay, now I get the error: TypeError 'module' object is not callable, for the line where I create the object: var1 = Class1(). – Kanerva Peter Jan 05 '18 at 15:29
  • Are your sure your `__int__.py` contains: `from .Class1 import Class1`? – Mike Müller Jan 05 '18 at 15:41
  • Ah sorry, it seems i got the error inside Class1's constructir where I create an object of Class2 which is in the same package. But It was solved by importing Class2 into Class1 with the leading dot notation: from .Class2 import Class2. Thanks!! – Kanerva Peter Jan 05 '18 at 15:49