@staticmethod vs module-level function

Posted by darkfeline on Programmers See other posts from Programmers or by darkfeline
Published on 2012-10-25T04:02:14Z Indexed on 2012/10/25 5:20 UTC
Read the original article Hit count: 215

Filed under:

This is not about @staticmethod and @classmethod! I know how staticmethod works. What I want to know is the proper use cases for @staticmethod vs. a module-level function.

I've googled this question, and it seems there's some general agreement that module-level functions are preferred over static methods because it's more pythonic. Static methods have the advantage of being bound to its class, which may make sense if only that class uses it. However, in Python functionality is usually organized by module not class, so usually making it a module function makes sense too.

Static methods can also be overridden by subclasses, which is an advantage or disadvantage depending on how you look at it. Although, static methods are usually "functionally pure" so overriding it may not be smart, but it may be convenient sometimes (though this may be one of those "convenient, but NEVER DO IT" kind of things only experience can teach you).

Are there any general rule-of-thumbs for using either staticmethod or module-level functions? What concrete advantages or disadvantages do they have (e.g. future extension, external extension, readability)? If possible, also provide a case example.

© Programmers or respective owner

Related posts about python