0% found this document useful (0 votes)
12 views

Init .Py

Python init

Uploaded by

Franklin Salvius
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Init .Py

Python init

Uploaded by

Franklin Salvius
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Mystery of

__init__.py

Ammar Munir
WHAT ?
The __init__.py file is used in Python to mark a directory as a package. A package
is a way of organizing related modules into a single directory hierarchy. By
including an __init__.py file in a directory, Python treats the directory as a
package, allowing you to import modules from it.

BUT !
Without an __init__.py file, a directory is not considered a package in older
versions of Python (before 3.3). However, starting from Python 3.3, implicit
namespace packages were introduced, which allow directories to be recognized
as packages without needing an __init__.py file.

Why we still use it ?

Ammar Munir
Here are the reasons why we still use
__init__.py in python3.3+

Initializing the Package Controlling imports

Providing a convenient interface Ensuring compatibility and clarity

Ammar Munir
Structure Initializing the Package

You can use __init__.py to

Module1 initialize the package. This

can include setting up

package-wide variables,

__init__.py

importing specific

submodules, or executing

main.py
package-level code.

output.py

Ammar Munir
Structure
Controlling imports

You can control what gets

Module1 imported when you use a

wildcard import (from

my_package import *). By

Module2

defining the __all__ list in

__init__.py, you specify which

modules or functions should

__init__.py

be accessible.

main.py

Ammar Munir
Structure
Providing a convenient interface

You can provide a more

convenient interface for

Module1

your package by exposing

selected functions or

Module1 classes at the package

level.

__init__.py

main.py

Ammar Munir
Structure Ensuring compatibility and clarity

Using __init__.py makes it

Module1 clear that the directory is

intended to be a package,

which can help with

compatibility and

understanding the

main.py
package structure.

Ammar Munir
Was it helpful ?

Like Comment Share Save

Ammar Munir
Python | Django | Web Engineer

You might also like