A real use for staticmethod

June 23, 2005

In Python, all method functions normally get called with the object as their first argument. New-style classes can specify that some methods should instead be 'static' methods: they don't receive the object as one of their arguments.

On the face of it this is a bit peculiar. Given that Python has ordinary (module-level) functions, why would you ever want to design a staticmethod instead (apart from misplaced object-oriented purity)?

What I use static methods for is as a way of having subclasses specify what piece of data from a data source a 'generic over a class of classes' method function will work on. The pattern looks like:

class Abstract(object):
   def frobnicate(self, datasource):
       work_on = self._pullfrom(datasource)
       # frobnicate work_on
   def fiddle(self, datasource):
       work_on = self._pullfrom(datasource)
       # fiddle with work_on
   # and so on

class RealA(Abstract):
   @staticmethod
   def _pullfrom(datasource):
       return datasource.thing_a()
class RealB(Abstract):
   @staticmethod
   def _pullfrom(datasource):
       return datasource.thing_b()

There are alternative patterns for this same effect, but none of them are as simple once the situation itself becomes more complex, such as needing more than one piece of information from the datasource.

Written on 23 June 2005.
« Future Sysadmin Jobs
An unchanging system should be stable »

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Thu Jun 23 02:40:34 2005
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.