How to properly organize "helper" methods for a class method

Viewed 990

I have a Python class that has several "major" methods, which successively modify one of its attributes, e.g.

def method1(self):
    # modify an attribute of self
    return self

def method2(self):
    # modify the same attribute of self
    return self 

Each of these core methods, in turn, calls multiple "helper" class methods that also modify the same attribute, i.e.

def method1(self):
    self = self.helper_method1().helper_method2()
    return self

def method2(self):
    self = self.helper_method3().helper_method4()
    return self 

Is there a consensus on where (on what level) these "helper" methods should be defined inside a class?

I.e. is this:

def helper_method1_to_be_called_by_method1(self):
    # modify at attribute of self
    return self

def helper_method2_to_be_called_by_method1(self):
    # modify at attribute of self
    return self

def method1(self):
    self = self.helper_method1().helper_method2()
    return self

preferable to this (or vice versa):

def method1(self):

    def helper_method1_to_be_called_by_method1(self):
        # modify at attribute of self
        return self

    def helper_method2_to_be_called_by_method1(self):
        # modify at attribute of self
        return self

    self = self.helper_method1().helper_method2()
    return self

Or is there a third strategy that works best in terms of performance, ease of readability, and maintenance?

2 Answers

The thing is that you never know how flexible your design should be. One extreme case will be to nest each and every related helper method (your approach #2). Another edge case is to put each helper method in a separate file (module) and call it something like "method1_helper_utils.py". Unless you know the exact software design in advance, I'd suggest to do it this way:

  1. Start with the approach #1
  2. If the main method combined with helper method becomes too big (> 20-30 loc, or whatever is a reasonable bound for you), or unreadable - make it the class method, as you described in you approach #2
  3. If the helper method becomes common for multiple functions in a class - again, make it the class method
  4. If the helper method becomes common for multiple classes in a module - put it in a separate file

Nested function has access to variables in their outer functions scope. It is so-called function closure. I believe that if this is not what you need than probably nested function is not needed in this case.

Related