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?
If you remove the __init__.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail. Leaving an __init__.py file empty is considered normal and even a good practice, if the package's modules and sub-packages do not need to share any code.
The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.
This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.
Although Python works without an __init__.py file you should still include one. It specifies that the directory should be treated as a package, so therefore include it (even if it is empty).
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
__init__.py
is for packages. A package contains a collection of related modules. If you just have a single module you want to use, you don't need to use __init__.py
; just put the single .py
file somewhere on the system path and you can import it.
The purpose of packages is not just to allow you to import the modules inside them. It's to group the modules together. The main benefit of this is that, if a module is inside a package, then that module can import other modules from the package using relative imports. If you have foo.py
and bar.py
in the same package, then foo
can just do from . import bar
. This makes intra-package imports more compact and easier to reorganize if you restructure the package or change its name.
Also, an obvious benefit is. . . if you make it a package, you don't have to do that sys.path
stuff every time you want to import something from it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With