search by tags

for the user

adventures into the land of the command line

What is the __init__.py file for in a python project?

Python has a core library with modules and packages that already have names, like ‘json’ and 'datetime’. It’s also possible to create your own user defined modules or packages, but you need to name them. A module is one file, and a package is a collection of files.

We can tell python that all of the files in this place are for this thing, by including an __init__.py file. That’s one reason, but what’s another?

What happens if you create your own package, but you name it the same thing as an already existing one?

$ mkdir datetime
$ touch datetime/__init__.py
$ touch datetime/datetime.py

$ python
>>> import sys
>>> sys.path.insert(0, './datetime/datetime')
>>> import datetime
>>> datetime.datetime.now()
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute 'datetime'

And if we delete the blank __init__.py file?

$ rm -f datetime/__init__.py*

$ python
>>> import sys
>>> sys.path.insert(0, './datetime/datetime')
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2017, 8, 19, 5, 24, 57, 411143)

So the __init__.py file lets you override and create your own packages which share the namespace of packages in the core library.