2

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?

nijshar28
  • 173
  • 7

2 Answers2

1

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
Sergey Dyshko
  • 315
  • 1
  • 5
  • Hey. Thanks for your reply. When you say "20-30 loc", do you mean the number of definitions? – nijshar28 Jul 08 '20 at 20:30
  • 1
    Here's a good explanation, @nijshar28, : https://stackoverflow.com/questions/611304/how-many-lines-of-code-should-a-function-procedure-method-have – Sergey Dyshko Jul 09 '20 at 07:29
1

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.

alex_noname
  • 26,459
  • 5
  • 69
  • 86