[Python-ideas] Good uses for staticmethod

Brett Cannon brett at python.org
Fri Jul 22 12:46:18 EDT 2016


On Fri, 22 Jul 2016 at 07:34 Edward Minnix <egregius313 at gmail.com> wrote:

> Hello,
>
> I have been reading Luciano Ramalho’s *Fluent Python, *and in the book he
> says he cannot think of a good use for staticmethod, I have been thinking
> about that, and so far I have only thought of one good use case: when you
> have a version of a common function, e.g., sum, and you want to qualify
> it with a better name but something like sumLineItems would sound wrong
> (to me at least). Would this be a good choice for something like:
>
> class LineItem:
> . . . . . . . .
> def __add__(self, other):
> ### Function body ###
>
> . . . . . . . .
>
> @staticmethod
> def sum(items: Sequence[LineItem]) -> LineItem:
> ### Add up LineItems ###
>
> Does this seem like a reasonable use for staticmethod? I think its a good
> way to qualify a name in a more concise way.
>

I don't think it is as I don't think it's any more concise than
sum_line_items().

The only reason I ever use staticmethod is if I have a method that doesn't
use self or cls but I expect subclasses to potentially need/want to
override the method. Otherwise whatever the staticmethod is should be a
function.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160722/61916131/attachment.html>


More information about the Python-ideas mailing list