Saturday, July 27, 2024

What’s __init__.py ? – Yasoob Khalid

[ad_1]

Okay yet one more helpful submit. This submit is admittedly essential and helpful for anybody simply beginning out with python. So what’s the __init__.py file ?

Recordsdata title __init__.py are used to mark directories on disk as Python bundle directories. When you have the next information:

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

and mydir is in your path, you’ll be able to 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 often empty, however can be utilized to export chosen parts of the bundle below extra handy title, maintain comfort features, and so on. Given the instance above, the contents of the init module could 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 stop 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 may 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

[ad_2]

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles