Module function vs staticmethod vs classmethod vs no decorators: Which idiom is more pythonic?

The most straightforward way to think about it is to think in terms of what type of object the method needs in order to do its work. If your method needs access to an instance, make it a regular method. If it needs access to the class, make it a classmethod. If it doesn’t need access to the class or the instance, make it a function. There is rarely a need to make something a staticmethod, but if you find you want a function to be “grouped” with a class (e.g., so it can be overridden) even though it doesn’t need access to the class, I guess you could make it a staticmethod.

I would add that putting functions at the module level doesn’t “pollute” the namespace. If the functions are meant to be used, they’re not polluting the namespace, they’re using it just as it should be used. Functions are legitimate objects in a module, just like classes or anything else. There’s no reason to hide a function in a class if it doesn’t have any reason to be there.

Leave a Comment