How to write a __init__ file in Python 3?

Asked

Viewed 514 times

4

I created a directory with 3 modules. As below:

operacoes
    __init__.py
    soma.py
    media.py

In my file __init__.py I have the following code:

from media import *

The module soma.py is used within the media.py, then I’ll have the import of it within the media. But this is ok.

My doubt is due to the error that is giving in from <module> import *, which is as follows:

File "C: Users Jaqueline Workspace python3 lib site-Packages operacoes__init__.py", line 1, in from media import * Modulenotfounderror: No module named 'media'

I’m doing the import wrong for Python 3? Is there anything else that could cause this error? I can’t understand what is wrong.

1 answer

2

Up to python 3.3 the files __init__.py denote namespaces for python packages. PEP 420 makes explicit in its Abstract "namespaces are mechanisms for separating a python package into several directories on disk." And this PEP came exactly to change this, from python 3.3 (PEP cited), the namespaces are implicit in Python, completely discarding the need for files __init__.py

In the examples you present in the question, if media.py needs to use something from the soma.py module, Voce can import implicta with *, or explicitly (most recommended) "Explicit is better than implicit"

In the media.py file:

# De forma implicita
from .soma import * 

# De forma explícita
from .soma import obj1, obj2 ....

Even in the earlier versions that require the presence of __init.py__, no need to write anything inside the file.

  • Ok. The fact is that I’m working on a package that I’m going to use in another application, and this package initializes some things in the project. I gave a simpler example, like operations. I would like to keep the init in my project, the problem is that I don’t know how to write the from ... import .... Always give me the error ModuleNotFoundError: No module named '<module>'. What is the right way to write?

  • Hi, I had a similar problem. Check two things: i) The directory name has to be different from the file name (eg.py operations/operations gives error). ii) PYTHONPATH has to be configured to run on the command line.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.