7

When creating a Python package, I am told to create a blank file called init.py. What I don't understand is why I need to create this file. The distutils build script doesn't modify it, so five builds later it's still blank. What is it's purpose?

Nathan2055
  • 2,283
  • 9
  • 30
  • 49
  • 4
    You really should at least look at the tutorial when you don't understand something. It's there for a reason. – abarnert May 14 '13 at 00:42
  • @abarnert - The tutorial I was using (http://guide.python-distribute.org/quickstart.html) didn't mention what it was for, just to create it. – Nathan2055 May 14 '13 at 02:45
  • 3
    That tutorial is for setting up your packages to be shared with other people. It more or less assumes that you already understand how packages work on a basic level. – Karl Knechtel May 14 '13 at 03:50
  • 1
    A cause for misunderstanding here is “package”: a Python package is a directory that can be imported as a module and contains other modules; this is related to imports, not to packaging. – merwok May 14 '13 at 16:28
  • @ÉricAraujo: It's a little confusing to novices that the same term is used for "directory that can be imported as a module" and for "thing you install from, e.g., PyPI, which may be a module, a package, or more than one of the above". – abarnert May 14 '13 at 19:19
  • We’re well aware of the confusing, and there is no magic solution :( – merwok May 14 '13 at 21:15
  • And if you want a quick laugh and to see this problem in action, read this chat log: http://chat.stackoverflow.com/rooms/6/conversation/nathan2055-packaging-noob – Nathan2055 May 15 '13 at 15:35

1 Answers1

5

It a signal to Python that the folder is a package, not just a folder. It also contains initialization code that is run when the package is imported into a script.

See the docs on the subject for more. The most relevant extract:

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.

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183