Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing modules in Python and __init__.py

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

like image 963
alwbtc Avatar asked May 06 '11 10:05

alwbtc


People also ask

Does init py import all modules?

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.

What is Python module __ init __ py?

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.

What should __ init __ py contain?

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.").


2 Answers

__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.

like image 140
Björn Pollex Avatar answered Oct 05 '22 19:10

Björn Pollex


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.

like image 38
cdarke Avatar answered Oct 05 '22 17:10

cdarke