osdir.com


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

__init__ patterns


On Thu, 30 Aug 2018 at 14:07, Tim <jtim.arnold at gmail.com> wrote:
>
> I saw a thread on reddit/python where just about everyone said they never put code in their __init__ files.
>
> 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. And I never do 'from whatever import *'
> Ever.
>
> The reddit people said they put all their stuff into different modules and leave init empty.
>
> What do you do?  I like my pattern but I'm willing to learn.

What matters is the user interface, not where you put your code
"behind the scenes". If your documented interface is

    import foo
    foo.do_something()

then it's perfectly OK (IMO) for do_something to be implemented in
foo/__init__.py. It's *also* perfectly OK for it to be implemented in
foo/internals.py and imported into __init__.py. Whatever makes your
development process easier. Of course, if you *document* that
do_something is available as foo.internals.do_something, then you can
no longer take the first option - that's up to you, though :-)

Conversely, if your package interface is

    import foo.utilities
    foo.utilities.do_something()

then do_something needs to be implemented in foo/utilities.py
(assuming utilities isn't itself a subpackage :-)) Whether you choose
to have a convenience alias of foo.do_something() in that case
determines whether you also need to import it in foo/__init__.py, but
that's fine.

tl;dr; Design your documented interface, and make sure that's as you
(and your users) want it. Don't let anyone tell you how you should
structure your internal code, it's none of their business.

Paul