Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using __init__.py

People also ask

What is the use of __ init __ py?

The __init__.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.

Is __ init __ py necessary?

If you have setup.py in your project and you use find_packages() within it, it is necessary to have an __init__.py file in every directory for packages to be automatically found.

Should __ init __ py be empty?

Leaving an __init__.py file empty is considered normal and even a good practice, if the package's modules and sub-packages do not need to share any code.

What is __ init __ py in flask?

The app/__init__.py file provides the interface to the app module. The module imports the Flask class from the flask module and in create_app(), which we saw in wsgi.py, a Flask object instance is created, has its application routes registered, and then is returned.


The vast majority of the __init__.py files I write are empty, because many packages don't have anything to initialize.

One example in which I may want initialization is when at package-load time I want to read in a bunch of data once and for all (from files, a DB, or the web, say) -- in which case it's much nicer to put that reading in a private function in the package's __init__.py rather than have a separate "initialization module" and redundantly import that module from every single real module in the package (uselessly repetitive and error-prone: that's obviously a case in which relying on the language's guarantee that the package's __init__.py is loaded once before any module in the package is obviously much more Pythonic!).

For other concrete and authoritative expressions of opinion, look at the different approaches taken in the various packages that are part of Python's standard library.


The contents of __init__.py are imported when you import a module within the package.

You're overlooking a third scenario, which is to put the common parts in a separate module and then have the other modules import that, leaving __init__.py for things that will be used outside the package. This is the practice I usually follow.