I have been reading about the function of __init__.py
file. It is said that we need an empty __init__.py
file in the folder which contains modules, so that these modules can be imported. However, I tried adding a folder path to PYTHONPATH (Environment Variable in Windows 7). Although this folder does not contain an __init__.py
file, I can still import the modules from that folder. Could you please explain how these modules can be imported without the existence of an __init__.py
?
Thanks,
Best regards
We can turn this directory into a package by introducing __init__.py file within utils folder. Within __init__.py , we import all the modules that we think are necessary for our project.
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.
The gist is that __init__.py is used to indicate that a directory is a python package. (A quick note about packages vs. modules from the python docs: "From a file system perspective, packages are directories and modules are files.").
__init__.py
turns a folder into a package. This is useful to create a sort of hierarchy of modules, where you can have import-statements like this:
import mymodule.cool.stuff
This is not possible without packages.
If a directory (folder) contains a __init__.py
file then it becomes a package. What you thought you read was not strictly correct, as you found. A package can be imported as if it was a module by itself, and any code in __init__.py
is run, although it is often empty. Packages are a way of grouping multiple modules together, and you can load them using:
import package-name.module-name
Packages can also be nested, and often are. Look in the Lib directory under your Python software directory for many examples.
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