Code in __init__.py, is it bad form?

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Feb 23 21:43:06 EST 2009


Michael Crute <mcrute at gmail.com> writes:

> Is it bad form (i.e. non-pythonic) to have code in your __init__.py
> files?

No, it's good form, but *only* for code that truly pertains to the
entire package. Anything that can reasonably be in a module other than
‘__init__’, should be.

That leaves the following things suitable for code in ‘__init__’,
OTTOMH:

* Metadata attributes for the package (e.g. version string).

* Docstring for the package

* ‘from foo import bar’ to present attributes of the package that are
  actually implemented in a module, which should be just about
  everything in the package.

> If you object to code in __init__.py why

I object only to code that isn't clearly “relates to the entire
package and can't reasonably be implemented in a separate module”.

If you're going to the effort of making a package (rather than just
coding the namespace as a single module), then the implementation
should be in modules other than ‘__init__’ to allow easier re-use,
re-factoring, and testing.

-- 
 \      “When I wake up in the morning, I just can't get started until |
  `\     I've had that first, piping hot pot of coffee. Oh, I've tried |
_o__)                                    other enemas...” —Emo Philips |
Ben Finney



More information about the Python-list mailing list