When to use Static Methods in Python? Never
See Python: Tips and Tricks for similar articles.The short answer is in the title. Never use static methods in Python.
The initial intention of this post was to provide a simple and concrete use case for a static method in Python. I started with this 12-year conversation about static methods on StackOverflow, which seemed promising. But it doesn’t contain a single practical use case. And I think I know why. There are none.
Creating a static method is straightforward enough, but as Nathan Tregillus sort of asks in this post, the real question is why would you ever want to?
In answer to a similar question about when to use static methods in Java, Associate Prof not-just-yeti wrote this short-and-sweet explanation:
One rule-of-thumb: ask yourself “does it make sense to call this method, even if no Obj has been constructed yet?” If so, it should definitely be static.
Initially, I thought that made sense. But, assuming you have decided to use an object-oriented rather than a procedural approach to coding, why would you ever want to call a method before instantiating an object?
Isn’t obj.method()
always better than Class.method(obj)
?
Or to give a more concrete example, wouldn’t you rather write -5.abs()
than Math.abs(-5)
as Miško Hevery suggests in Static Methods are Death to Testability?
Multiple Arguments
In Java, I can see how it is helpful to call a method on a class when you want to pass in multiple arguments. For example, Math.max(5, 7)
. But why does this need to be a static method? In Python, you could just make it a class method, only callable on the class itself and not on instances of a class.
The Math
class in Java is basically just a grouping of math-related utility methods. In Python, this is generally handled via modules (e.g., the math
module), not classes.
Incidentally, in this discussion, Google Senior Software Developer and author of C# in Depth, Jon Skeet explains why he thinks static methods in Java should have been designed to behave like class methods in Python do and should not be callable on instance objects.
Built-in Static Methods in Python
It’s hard to find an example of a practical use of a static method in Python. I found two examples of static methods built in to Python:
- str.maketrans() – I cannot understand why this is a static rather than a class method. The
str
class object is always available in Python, so why would you want to callmaketrans()
on an instance ofstr
? - importlib.abc.InspectLoader.source_to_code() – This was made static in Python 3.5 to “make it easier to work with source code in a string“.
I’m sure there are other examples, but I bet they are all equally obscure and not worth the time it takes to type “@staticmethod”.
So, are static methods completely useless in Python? Guido van Rossum basically said as much in April, 2012:
We all know how limited static methods are. (They’re basically an accident — back in the Python 2.2 days when I was inventing new-style classes and descriptors, I meant to implement class methods but at first I didn’t understand them and accidentally implemented static methods first. Then it was too late to remove them and only provide class methods.
So, if you’re wondering if you should make one of your Python methods static, as far as I can tell, you shouldn’t do it. Ever. Right?
Related Articles
- Fixing WebVTT Times with Python
- Using Python to Convert Images to WEBP
- Scientific Notation in Python
- Understanding Python’s __main__ variable
- Converting Leading Tabs to Spaces with Python
- pow(x, y, z) more efficient than x**y % z and other options
- A Python Model for Ping Pong Matches
- Bulk Convert Python files to IPython Notebook Files (py to ipynb conversion)
- Python’s date.strftime() slower than str(), split, unpack, and concatenate?
- Basic Python Programming Exercise: A Penny Doubled Every Day
- Bi-directional Dictionary in Python
- How to find all your Python installations on Windows (and Mac)
- Associate Python Files with IDLE
- Change Default autosave Interval in JupyterLab
- Python: isdigit() vs. isdecimal()
- Python Clocks Explained
- Python Color Constants Module
- Maximum recursion depth exceeded while calling a Python object
- When to use Static Methods in Python? Never (this article)
- Finally, a use case for finally – Python Exception Handling
- Creating an Email Decorator with Python and AWS
- Python Coding Challenge: Two People with the Same Birthday
- How to Create a Simple Simulation in Python – Numeric Data
- Collatz Conjecture in Python
- Simple Python Script for Extracting Text from an SRT File
- Python Virtual Environments with venv
- Mapping python to Python 3 on Your Mac
- How to Make IDLE the Default Editor for Python Files on Windows
- How to Do Ternary Operator Assignment in Python
- How to Convert Seconds to Years with Python
- How to Create a Python Package
- How to Read a File with Python
- How to Check the Operating System with Python
- How to Use enumerate() to Print a Numbered List in Python
- How to Repeatedly Append to a String in Python
- Checking your Sitemap for Broken Links with Python
- How to do Simultaneous Assignment in Python
- Visual Studio Code - Opening Files with Python open()
- How to Slice Strings in Python
- How Python Finds Imported Modules
- How to Merge Dictionaries in Python
- How to Index Strings in Python
- How to Create a Tuple in Python