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?
- 4You really should at least look at the tutorial when you don't understand something. It's there for a reason.abarnert– abarnert2013-05-14 00:42:42 +00:00Commented May 14, 2013 at 0:42
- @abarnert - The tutorial I was using (guide.python-distribute.org/quickstart.html) didn't mention what it was for, just to create it.Nathan2055– Nathan20552013-05-14 02:45:46 +00:00Commented May 14, 2013 at 2:45
- 3That 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– Karl Knechtel2013-05-14 03:50:43 +00:00Commented May 14, 2013 at 3:50
- 1A 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– merwok2013-05-14 16:28:03 +00:00Commented May 14, 2013 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– abarnert2013-05-14 19:19:04 +00:00Commented May 14, 2013 at 19:19
1 Answer
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__.pyfiles are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such asstring, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case,__init__.pycan just be an empty file, but it can also execute initialization code for the package or set the__all__variable, described later.