Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is an empty __init__.py file correct?

Tags:

python

I have several, empty, __init__.py files in my packages. Is it correct if I keep them empty or do I have to place a pass inside them?

Are there any PEP, or other, guidelines about the subject?

like image 340
tapioco123 Avatar asked Jun 02 '12 14:06

tapioco123


People also ask

Can the init py file be empty?

An __init__.py file can be blank. Without one, you cannot import modules from another folder into your project. The role of the __init__.py file is similar to the __init__ function in a Python class. The file essentially the constructor of your package or directory without it being called such.

What should be in the __ init __ py file?

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.

Do we still need __ init __ py?

It's crucial that there are no __init__py files in the google and google/cloud directories so that both directories can be interpreted as namespace packages. In Python 3.3+ any directory on the sys.


1 Answers

Empty files are perfectly fine:

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.

Depending on what you plan to do it's a good place to import public stuff from the modules in your package so people can simply use from yourpackage import whatever instead of having to use from yourpackage.somemodule import whatever.

like image 129
ThiefMaster Avatar answered Sep 21 '22 02:09

ThiefMaster