[Tutor] what do you use @staticmethod for?

Tim Golden mail at timgolden.me.uk
Thu Nov 20 09:58:34 CET 2008

spir wrote:
> Good night,
> I have not yet found any use for this feature.
> Also, I do not really understand the difference with @classmethod, from 
> the programmer's points of view (even if I get the difference on the 
> python side).
> As I see it, a classmethod is a very ordinary method, except its 'owner' 
> is a type. [But we cannnot express its definition with standard syntax, 
> because it conflicts with instance method definition syntax.]
> I would be pleased to read your views about staticmethods, and the use 
> cases you have for them -- that could not be done (the same way) with 
> classmethods.

For me, the difference is a somewhat conceptual one: I use class methods
when the operation they're performing is not (possibly cannot be) tied to 
a specific instance of that class. The canonical application is as a class
factory. So I have classmethods called things like .from_string which
return an instance of the class which is their first parameter. This will
therefore work from subclasses.

On the other side of the coin, static methods don't (and can't) even rely 
on the class they're in so they're not very different from, say, module
global functions. I use them if they are in concept a part of whatever
functionality the class is offering, but don't (and shouldn't) depend 
on any instance or any class data. Examples in my own code include a
method which returns login sessions from the Windows LSA within an LSA
class: you don't need any kind of LSA policy handle to enumerate logons,
but it fits conceptually within the idea of an LSA class whose other
operations do rely on a policy handle, so I left it there and made it



More information about the Tutor mailing list