__init__ patterns

Terry Reedy tjreedy at udel.edu
Thu Aug 30 15:29:31 EDT 2018


On 8/30/2018 9:43 AM, Steven D'Aprano wrote:
> 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-
> package-init-py-files
>>
>> 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):
> 
> https://github.com/python/cpython/tree/3.7/Lib

tkinter.__init__ has 'from tkinter.constants import *' and has the code 
defining tk widgets, among other things.  tkinter/ has submodules for 
ttk, fonts, and other optional facilities.  The setup is partly for 
historical reasons, but is partly intended and not a bad design for a 
module with 'main' stuff and 'optional' stuff.

The user interface would be the same if widget code were in 
tkinter.widgets with .__init__ containing 'from tkinter.widgets import *'.

-- 
Terry Jan Reedy




More information about the Python-list mailing list