views:

535

answers:

7

I have a Python class full of static methods. What are the advantages and disadvantages of packaging these in a class rather than raw functions?

+23  A: 

There are none. This is what modules are for: grouping related functions. Using a class full of static methods makes me cringe from Javaitis. The only time I would use a static function is if the function is an integral part of the class. (In fact, I'd probably want to use a class method anyway.)

Benjamin Peterson
A: 

I agree with Benjamin. Rather than having a bunch of static methods, you should probably have a bunch of functions. And if you want to organize them, you should think about using modules rather than classes. However, if you want to refactor your code to be OO, that's another matter.

toby
A: 

Not only are there no advantages, but it makes things slower than using a module full of methods. There's much less need for static methods in python than there is for them in java or c#, they are used in very special cases.

Vasil
+9  A: 

No. It would be better to make them functions and if they are related, place them into their own module. For instance, if you have a class like this:

class Something(object):

    @staticmethod
    def foo(x):
        return x + 5

    @staticmethod
    def bar(x, y):
        return y + 5 * x

Then it would be better to have a module like,

# something.py

def foo(x):
    return x + 5

def bar(x, y):
    return y + 5 * x

That way, you use them in the following way:

import something
print something.foo(10)
print something.bar(12, 14)

Don't be afraid of namespaces. ;-)

Evan Fosmark
A: 

Classes are only useful when you have a set of functionality than interacts with a set of data (instance properties) that needs to be persisted between function calls and referenced in a discrete fashion.

If your class contains nothing other than static methods, then your class is just syntactic cruft, and straight functions - possibly with module globals, only if necessary - are clearer and all that you need.

Daniel
+2  A: 

If your functions are dependent on each other or global state, consider also the third approach:

class Something(object):
    def foo(self, x):
        return x + 5

    def bar(self, x, y):
        return y + 5 * self.foo(x)

something = Something()

Using this solution you can test a function in isolation, because you can override behavior of another function or inject dependencies using constructor.

Adam Dziendziel
A: 

Depends on the nature of the functions. If they're not strongly unrelated (minimal amount of calls between them) and they don't have any state then yes I'd say dump them into a module. However, you could be shooting yourself in the foot if you ever need to modify the behavior as you're throwing inheritance out the window. So my answer is maybe, and be sure you look at your particular scenario rather then always assuming a module is the best way to collect a set of methods.

Mark Roddy