mister.elastic
mister.elastic

Reputation: 417

Python: make private class methods always static if possible?

I know it is good style in other languages (C#, JAVA, ...) to make "private" methods (using two underscores) static if possible. Is there any recommendation for Python?

I would rather not make them static, because they are only private (I don't want to move them to utility classes and they are not performance relevant) and I want to avoid cluttering my code with decorators. On the other hand, the static code analyzer tells me to do so (and I want to write code in the "Pythonic" way).

Upvotes: 2

Views: 1492

Answers (2)

Webucator
Webucator

Reputation: 2693

The short answer is you should almost never use static methods in Python. They were added by mistake.

I meant to implement class methods but at first I didn't understand them and accidentally implemented static methods first. - Guido van Rossum

You can almost definitely achieve what you want with a class method or an instance method.

More on why static methods in Python are mostly useless here.

Upvotes: 2

sc3w
sc3w

Reputation: 1164

In python there is no such thing like 'private method', all methods are public. The only thing that tells you that a method is not intended to use publicly is that it's name starts with an underscore.

If your methods are not referencing anything from self (an instance of the class) then you could make them static to optimize the memory usage of your application.

Upvotes: 0

Related Questions