[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

__init__ patterns

On Thu, 30 Aug 2018 06:01:26 -0700, Tim wrote:

> I saw a thread on reddit/python where just about everyone said they
> never put code in their __init__ files.

Pfft. Reddit users. They're just as bad as Stackoverflow users. *wink*

> Here's a stackoverflow thread saying the same thing.
> https://stackoverflow.com/questions/1944569/how-do-i-write-good-correct-
> That's new to me. I like to put functions in there that other modules
> within the module need. Thought that was good practice DRY and so forth.

Its fine to put code in __init__.py files.

If the expected interface is for the user to say:

result = package.spam()

then in the absence of some specific reason why spam needs to be in a 
submodule, why shouldn't it go into package/__init__.py ?

Of course it's okay for the definition of spam to be in a submodule, if 
necessary. But it shouldn't be mandatory.

> And I never do 'from whatever import *' Ever.
> The reddit people said they put all their stuff into different modules
> and leave init empty.

Did any one of them state *why* they do this? What benefit is there to 
make this a hard rule?

Did anyone mention what the standard library does?

Check out the dbm, logging, html, http, collections, importlib, and 
curses packages (and probably others):


Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson