Friday, March 1, 2024
HomePythonWhat's __init__.py ? - Yasoob Khalid

What’s __init__.py ? – Yasoob Khalid


Okay yet one more helpful put up. This put up is basically necessary and helpful for anybody simply beginning out with python. So what’s the __init__.py file ?

Information title __init__.py are used to mark directories on disk as Python bundle directories. You probably have the next information:

mydir/spam/__init__.py
mydir/spam/module.py

and mydir is in your path, you may import the code in module.py as

import spam.module

or

from spam import module

When you take away the __init__.py file, Python will not search for submodules inside that listing, so makes an attempt to import the module will fail.

The __init__.py file is normally empty, however can be utilized to export chosen parts of the bundle beneath extra handy title, maintain comfort capabilities, and so forth. Given the instance above, the contents of the init module might be accessed as

import spam

And eventually here’s what the official documentation has to say about this file:

The __init__.py information are required to make Python deal with the directories as containing packages; that is performed to forestall directories with a typical title, comparable to string, from unintentionally hiding legitimate modules that happen afterward the module search path. Within the easiest case, __init__.py can simply be an empty file, however it could actually additionally execute initialization code for the bundle or set the __all__ variable, described later.

Supply : http://effbot.org/pyfaq/what-is-init-py-used-for.htm

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments