Source

What is __init__.py ?

Okay yet another useful post. This post is really important and useful for anyone just starting out with python. So what is the __init__.py file ?

Files name __init__.py are used to mark directories on disk as Python package directories. If you have the following files:

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

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

import spam.module

or

from spam import module

If you remove the __init__.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.

The __init__.py file is usually empty, but can be used to export selected portions of the package under more convenient name, hold convenience functions, etc. Given the example above, the contents of the init module can be accessed as

import spam

And finally here is what the official documentation has to say about this file:

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

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

Newsletter

×

If you liked what you read then I am sure you will enjoy a newsletter of the content I create. I send it out every other month. It contains new stuff that I make, links I find interesting on the web, and occasional discount coupons for my book. Join the 5000+ other people who receive my newsletter:

I send out the newsletter once every other month. No spam, I promise + you can unsubscribe at anytime

✍️ Comments

Mauro

there is a typo in one of your mydir, it is spelled as midir.

Yasoob
In reply to Mauro

Thanks for pointing it out Mauro. I just fixed it :)

Dipendra

Hi Yasoob, Thank you for writing this article. It is really helpful for me.

Say something

Send me an email when someone comments on this post.

Thank you!

Your comment has been submitted and will be published once it has been approved. 😊

OK