Python - why can I import modules without __init__.py at all?

laukok picture laukok · Aug 22, 2015 · Viewed 19.1k times · Source

I'm new to Python and I still can't get my head around why we need a __init__.py file to import modules. I have gone through other questions and answers, such as this.

What confuses me is that I can import my modules without __init__py, so why do I need it at all?

My example,

index.py
   modules/
      hello/
          hello.py
          HelloWorld.py

index.py,

import os
import sys

root = os.path.dirname(__file__)
sys.path.append(root + "/modules/hello")

# IMPORTS MODULES
from hello import hello
from HelloWorld import HelloWorld

def application(environ, start_response):

    results = []

    results.append(hello())

    helloWorld = HelloWorld()
    results.append(helloWorld.sayHello())

    output = "<br/>".join(results)

    response_body = output

    status = '200 OK'

    response_headers = [('Content-Type', 'text/html'),
                       ('Content-Length', str(len(response_body)))]

    start_response(status, response_headers)

    return [response_body]

modules/hello/hello.py,

def hello():
    return 'Hello World from hello.py!'

modules/hello/HelloWorld.py,

# define a class
class HelloWorld:
    def __init__(self):
        self.message = 'Hello World from HelloWorld.py!'

    def sayHello(self):
        return self.message

Result,

Hello World from hello.py!
Hello World from HelloWorld.py!

What it takes is just these two lines,

root = os.path.dirname(__file__)
sys.path.append(root + "/modules/hello")

Without any of __init__py. Can someone explain why it works in this way?

If __init__py is the proper way, what should I do/change in my code?

Answer

Tzeeeentch picture Tzeeeentch · Aug 10, 2017

Based on this link: Since Python 3.3

Allowing implicit namespace packages means that the requirement to provide an __init__.py file can be dropped completely