4

I can import from subdirectories with a blank __init__.py file. That works fine. I think that init file in python works like an index file. But I really don't understand why the __init__.py file is blank to import. How do __init__.py file and importing really work?

What have to be __init__.py files content?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
alpi
  • 173
  • 1
  • 4
  • 14

2 Answers2

3

The __init__.py has two main functions:

  • Marking packages: It marks a directory as a Python package, and the inner .py files as Python modules.

  • Initialization code: As its name suggests, any code inside the __init__.py is automatically executed when the package is imported. This is the right place to run initialization code required for a certain package; however, it's perfectly OK to leave the __init__.py file empty.

Adam Matan
  • 128,757
  • 147
  • 397
  • 562
1

The subdirectory that you are importing from is a package if it has an __init__.py file in it. You don't need to use packages, you can just add the subdirectory to the sys.path list. However they are a neat way of keeping related modules together and are generally encouraged.

The __init__.py file has a similar purpose to the __init__ in a class, it initialises the package. This enables attributes to be given to the package, and __all__ is an example (list of exported names for import *).

There is sometimes no initialisation required, so it can be empty. A good place to look for examples is in the standard library subdirectories of the Lib directory. There you will find huge __init__.py files, and others that are empty.

Whether this is mandatory or not depends on the Python version. From Python 3.3 the __init__.py is not mandatory, and such packages are called Namespace Packages, see PEP0420. This means that a package can span directories, but there is a price to pay. There can be no __init__.py initialisation code and you don't get a __file__ attribute for the package. So unless you specifically need to span directories it is probably better to stick with regular packages.

cdarke
  • 42,728
  • 8
  • 80
  • 84