Search code examples
pythonpython-module

Use classes or modules to group static like methods?


I have ~30 methods (~6 logical groupings with ~5 methods per group) which only do calculations based on parameters passed, they do not save state or need anything else beside parameter values.

What is the more pythonic and better way of grouping this methods, using modules, or classes with static methods?

Difference will be :

from projectname.algorithms.module1 import method1, method2

and :

from projectname.algorithms import Group1
...
Group1.method1(parameter1)
...
Group1.method2(parameter1)

This are just example class, module and method names. Grouping with classes seems more logical to me. Is there any drawback to this way if this methods are accessed very frequently, or any other caveat?


Solution

  • You can import a module into your namespace like you can any object:

    from projectname.algorithms import module1
    
    
    module1.method1(parameter1)
    
    module1.method2(parameter1)
    

    so from an API perspective there is no difference between using a class with static methods, or a module here.

    The difference is only in the writing and maintenance.

    Here, stick to modules over static class methods. Use classes only for when you have some actual state to share. If you were to use classes to group these methods, you do create an expectation that the class objects themselves have some meaning beyond facilitating a namespace grouping.