Question

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?

Was it helpful?

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.

OTHER TIPS

Modules are just objects that stick themselves in sys.modules.

If you use a class you are going to have the ability to initialise it, and personally that's very confusing: when you provide functionality it should do something. You could always use throwaway classes that you initialise, but that's a bit of a hassle.

I've used both methods in a sense; I used a decorator to change a class into a namespace (def namespace(cls): return cls()) but it felt like a hack and I wouldn't really recommend it. It depends on the size of your namespaces.

If your namespaces are medium-to-large, favour modules. If you have many small modules it's then your choice. If you use classes, either make it well known not to initialise them (overload __init__ to throw errors) or initialise them. Also, since you're not using them as classes I'd suggest not using ClassNamingSchemes, but module_naming_schemes. If it quacks like a module and it tastes like a module, then damnit I'm making module soup tonight!

Apologies for the lack of coherence in this post.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top