Grouping related functions in Python -
suppose have module functions spam
, ham
use functions eggs
, foo
.
def spam(): eggs() foo() ... def ham(): eggs() foo() ...
now, eggs
, foo
used spam
, ham
, , doesn't make sense expose them @ module level. change names _eggs
, _foo
indicate internal use doesn't establish relation between spam
, ham
, eggs
, foo
.
so, make container class hold these functions this:
class spamham: @staticmethod def _eggs(): ... @staticmethod def _foo(): ... @staticmethod def spam(): ... @staticmethod def ham(): ...
but seems skethy because expect users not instantiate spamham
, use call static methods. plus doesn't seem right use class when want establish relation between methods.
i create separate module called spamham
, put these 4 functions that, spam
, ham
'belong' module in.
so, correct way establish such relations in python?
in general, advise not think of these things specific relations between functions. function should be self-contained unit of code1. central thesis here shouldn't think of eggs
belonging spam
, ham
. eggs
shouldn't care if gets called spam
or ham
or bacon
or toast
. important thing eggs
has name possible gives immediate idea function does2.
the trick figure out functions want people on outside have access ... determines whether it's eggs
(public) or _eggs
(implementation detail change without notice) you've alluded to.
1this isn't functions can't call other functions
2preferably correct idea function does... :)
Comments
Post a Comment