Python - Should I put my helper functions inside or outside the class?

PythonClassPylint

Python Problem Overview


In Python, if some methods of a class need a helper function, but the helper function itself doesn't use anything in the class, should I put the helper function inside or outside the class?

I tried putting it inside but PyLint was complaining that this function could have been put outside.

@Karl:

The class is a software upgrader and the helper function creates a new folder if the folder doesn't exist yet. The class is in a module having pretty much only the code for the class as of now. Other classes may be added later on.

Python Solutions


Solution 1 - Python

When deciding where to put helper functions the question I ask is, "Is it only for this class?" If it can help in other places, then it goes at the module level; if it is indeed only for this class, then it goes in the class with either staticmethod (needs no class data to do its job) or classmethod (uses some class, but not instance, data to do its job).

Another python code checker is pyflakes.

Solution 2 - Python

It's possible that the helper function better fits in at the module level rather than the class.

If you don't agree that this is the case, there is a staticmethod decorator that you can use on functions inside of the class. Simply put, a static method behaves the same between object instantiations of the same class. It does not rely on instance data.

For this reason, the staticmethod decorator renders behavior on the function such that it does not take an implicit first argument (typically self) as stated in the documentation).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJack ZView Question on Stackoverflow
Solution 1 - PythonEthan FurmanView Answer on Stackoverflow
Solution 2 - PythonBrianView Answer on Stackoverflow