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?

1
  • 1
    Because it's required by Python specification? Commented May 19, 2015 at 10:54

2 Answers 2

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.

4
  • Is this not a duplicate? Commented May 19, 2015 at 10:59
  • Thanks for the answer Adam! That clered question marks in my mind.
    – alpi
    Commented May 19, 2015 at 11:05
  • @alpi Sure. If it's the right answer, don't forget to mark it as accepted so that other users won't spend time on it.
    – Adam Matan
    Commented May 19, 2015 at 11:08
  • @PeterWood Not as far as I know.
    – Adam Matan
    Commented May 19, 2015 at 11:09
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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.