Jayanth Koushik
Jayanth Koushik

Reputation: 9904

Grouping related functions in Python

Suppose I have a module with functions spam and ham which use functions eggs and foo.

def spam():
    eggs()
    foo()
    ...

def ham():
    eggs()
    foo()
    ...

Now, eggs and foo are only used by spam and ham, and so it doesn't make sense to expose them at the module level. I could change their names to _eggs and _foo to indicate that they are for internal use but this doesn't really establish the relation between spam, ham, eggs and foo.

So, I could make a container class to hold these functions like this:

class SpamHam:

    @staticmethod
    def _eggs():
        ...

    @staticmethod
    def _foo():
        ...

    @staticmethod
    def spam():
        ...        

    @staticmethod
    def ham():
        ...

But this seems skethy because I expect users not to instantiate SpamHam and only use it to call the static methods. Plus it doesn't really seem right to use a class when all I want is to establish some relation between its methods.

I could create a separate module called spamham and put these four functions into that, but spam and ham really do 'belong' to the module they are already in.

So, what is correct way to establish such relations in Python?

Upvotes: 1

Views: 147

Answers (1)

mgilson
mgilson

Reputation: 309949

In general, I would advise to not think of these things as specific relations between functions. A function should be a self-contained unit of code1. My central thesis here is that you shouldn't think of eggs as belonging to spam and ham. eggs shouldn't care if it gets called by spam or ham or bacon or toast. The important thing is that eggs has a name that as clearly as possible gives you an immediate idea what the function does2.

The trick is to figure out which functions you want people on the outside to have access to ... That determines whether it's eggs (Public) or _eggs (Implementation detail that could change without notice) as you've already alluded to.

1This isn't to say that functions can't call other functions
2Preferably the correct idea about what the function does... :)

Upvotes: 4

Related Questions