How to write __init__ file in Python 3?

Question:

I created a directory with 3 modules. As below:

operacoes
    __init__.py
    soma.py
    media.py

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

from media import *

The soma.py module is used inside media.py , so I will import it inside media. But that's ok.

My question is due to the error that is being given in the from <module> import * , which is the following:

File "C:\Users\jaqueline\workspace\python3\lib\site-packages\operacoes__init__.py", line 1, in from media import * ModuleNotFoundError: No module named 'media'

Am I doing the wrong import to Python 3? Is there anything else that could generate this error? I cannot understand what is wrong.

Answer:

Until python 3.3 the __init__.py files denote namespaces for python packages. PEP 420 explains in its abstract "namespaces are mechanisms for separating a python package into several directories on disk." And this PEP came exactly to change that, as of python 3.3 (PEP cited), namespaces are implicit in Python, completely eliminating the need for __init__.py files

In the examples you present in the question, if media.py needs to use something from the soma.py module, you can import implicitly 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 earlier versions that require __init.py__ , there is no need to write anything inside the file.

Scroll to Top