Sub topic 4
Static methods: functions that live in a class namespace
A static method is an ordinary function that you store inside a class body. It receives no self and no cls. Python skips its usual automatic first argument for it. This chapter covers how static methods are defined and called, what they can and cannot see, how they behave under inheritance, and the mistakes people make with them.
Prerequisites
This chapter assumes you can already do the following:
- Define a class with
__init__and instance methods that useself. - Read the
@namedecorator syntax above a function. - Tell class attributes from instance attributes.
- Recognize the
@classmethoddecorator from the previous chapter, where a method receivesclsinstead ofself.
The working model
Every method defined in a class body starts as a plain function. What differs is what happens when you look the function up through the class or an instance. For a plain function, Python binds the instance as the first argument. For a class method, it binds the class. For a static method, it binds nothing and hands you the original function unchanged.
You mark a static method with the @staticmethod decorator:
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
@staticmethod
def is_valid(celsius):
return celsius >= -273.15
print(Temperature.is_valid(-300)) # False
print(Temperature.is_valid(25)) # Trueis_valid takes one parameter, celsius, and that is exactly the one argument you pass. No instance exists in the first call, and none is needed. The method is called on the class and behaves like any function.
The method sits in Temperature because it belongs to the topic of temperatures. It could equally be a module-level function. Putting it in the class groups related code and makes the call site read Temperature.is_valid(...), which tells the reader where the rule comes from.
What a static method receives
Compare the three method kinds side by side:
| Kind | Decorator | First argument | Can read instance state | Can read class state |
|---|---|---|---|---|
| Instance method | none | the instance (`self`) | yes | yes, through `self` or `type(self)` |
| Class method | `@classmethod` | the class (`cls`) | no | yes |
| Static method | `@staticmethod` | nothing extra | no | only by naming the class explicitly |
The last cell matters. A static method has no automatic link to the class it lives in. It can reach Temperature.something only because Temperature is a global name it looks up like any other. That is a hard-coded reference, and it has consequences under inheritance, which we cover below.
Calling a static method
You can call a static method on the class or on an instance. Both calls give the same result and pass the same arguments:
class Temperature:
@staticmethod
def is_valid(celsius):
return celsius >= -273.15
t = Temperature()
print(Temperature.is_valid(10)) # True
print(t.is_valid(10)) # True
print(type(Temperature.__dict__["is_valid"]).__name__) # staticmethodThe last line shows where the method really lives. Looking inside the class dictionary directly, you find a staticmethod object rather than a plain function. This wrapper object is what changes the lookup behavior.
The wrapper controls what normal attribute access returns. When you write Temperature.is_valid or t.is_valid, Python asks the wrapper for its value, and the wrapper returns the original function with nothing bound to it. You can confirm that:
class Temperature:
@staticmethod
def is_valid(celsius):
return celsius >= -273.15
t = Temperature()
wrapper = Temperature.__dict__["is_valid"]
print(Temperature.is_valid is wrapper.__func__) # True
print(t.is_valid is wrapper.__func__) # True
print(Temperature.is_valid is t.is_valid) # TrueAll three expressions refer to one function object. That is the defining property of a static method. Compare it with an instance method, where t.method creates a new bound-method object on each access.
Calling a static method from other methods
Inside the class, a static method is reached like any other attribute. Which prefix you use changes how it behaves under inheritance, so it matters.
class Temperature:
def __init__(self, celsius):
if not self.is_valid(celsius):
raise ValueError(f"{celsius} is below absolute zero")
self.celsius = celsius
@staticmethod
def is_valid(celsius):
return celsius >= -273.15
print(Temperature(20).celsius) # 20
try:
Temperature(-500)
except ValueError as error:
print(error) # -500 is below absolute zero__init__ calls self.is_valid(celsius). Python finds is_valid through the instance, gets the unbound function, and calls it with one argument. The call does not pass self along. This is the usual way to call a static method from an instance method.
There are three ways to write the call:
self.is_valid(x)looks up the method on the instance's class, so a subclass override is used.type(self).is_valid(x)does the same and is useful when you want to make the class lookup explicit.Temperature.is_valid(x)always uses the version inTemperature, even whenselfis an instance of a subclass.
From a class method, use cls.is_valid(x) for the same reason self.is_valid(x) is preferred in instance methods.
Static methods and inheritance
Subclasses inherit static methods, and they can override them. The override is chosen by the usual attribute lookup, so the choice depends on how you call the method.
class Parser:
@staticmethod
def clean(text):
return text.strip()
def parse(self, text):
return self.clean(text).split(",")
class LowerParser(Parser):
@staticmethod
def clean(text):
return text.strip().lower()
print(Parser().parse(" A,B ")) # ['A', 'B']
print(LowerParser().parse(" A,B ")) # ['a', 'b']parse calls self.clean. For a LowerParser instance, lookup finds LowerParser.clean first, so the override runs. Now change parse to call Parser.clean(text) instead. The override would be ignored for every subclass, because the name Parser is fixed in the source. This is the static-method version of the hard-coded class name problem that cls solves for class methods.
Two details to keep in mind:
- An override must also be declared with
@staticmethod. If the subclass writesdef clean(self, text)without the decorator, the method is now an instance method with a different signature, andself.clean(text)still works, butParser.clean(text)style calls on the subclass will break. - Static methods do not know which subclass they were called through.
LowerParser.clean(" X ")runs the function with" X "and nothing else. If the method needs to know the calling class, make it a class method.
The diagram shows what each way of reaching a method passes in.
Static methods versus module-level functions
A static method does the same job as a function defined at module level. The difference is where the name lives. Choose based on the following.
- Discoverability. A reader looking at
Temperatureseesis_validlisted with the other behavior of that type, andhelp(Temperature)shows it. - Namespace. Two classes can each have
parseorvalidatewithout clashing. At module level you would needparse_dateandparse_time, or separate modules. - Overriding. A subclass can replace a static method, and callers using
self.name(...)pick up the replacement. A module-level function cannot be overridden this way. - Import cost. A module-level function can be imported and used on its own. A static method requires importing the class.
If the helper is used by one class only, and is conceptually part of that class's job, a static method is a reasonable fit. If it is general-purpose, or used by many unrelated classes, a module-level function is simpler. Python does not need a class for every function, and many experienced developers default to module-level functions unless there is a reason to attach them.
A worked example
Here is a class that uses a static method for a pure helper and an instance method for state:
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = self._check_amount(balance)
@staticmethod
def _check_amount(amount):
if amount < 0:
raise ValueError("amount must not be negative")
return amount
def deposit(self, amount):
self.balance += self._check_amount(amount)
def withdraw(self, amount):
amount = self._check_amount(amount)
if amount > self.balance:
raise ValueError("insufficient funds")
self.balance -= amount
account = Account("Ada", 100)
account.deposit(50)
account.withdraw(30)
print(account.balance) # 120
try:
account.deposit(-5)
except ValueError as error:
print(error) # amount must not be negative_check_amount uses no instance data. It takes a number, validates it, and returns it. Declaring it static states that fact in the code: a reader knows it cannot change self.balance, and a test can call Account._check_amount(5) without building an account. The leading underscore is a convention that marks the method as internal to the class.
Static methods that need class data
Sometimes a helper needs a constant defined on the class. A static method can reach it by naming the class:
class Temperature:
ABSOLUTE_ZERO = -273.15
@staticmethod
def is_valid(celsius):
return celsius >= Temperature.ABSOLUTE_ZERO
print(Temperature.is_valid(0)) # TrueThis works, but it ties the method to the name Temperature. A subclass that sets its own ABSOLUTE_ZERO would still be checked against the parent's value. When a method needs to read class attributes and respect subclass overrides, write it as a class method:
class Temperature:
ABSOLUTE_ZERO = -273.15
@classmethod
def is_valid(cls, celsius):
return celsius >= cls.ABSOLUTE_ZEROA good rule: the moment a static method names its own class, ask whether it should receive cls instead.
Combining with other decorators
A static method can be wrapped by other decorators. Order matters, because each decorator wraps whatever is below it. Put @staticmethod on the outside:
import functools
class Sequence:
@staticmethod
@functools.cache
def fib(n):
return n if n < 2 else Sequence.fib(n - 1) + Sequence.fib(n - 2)
print(Sequence.fib(50)) # 12586269025The cache decorator wraps the function first. staticmethod then wraps the cached function and stops Python from binding an instance to it. If you reverse the order, cache receives a staticmethod object. In current Python versions that object is callable, so some reversed cases happen to work, but the code is fragile and misleading, so keep @staticmethod as the outermost decorator.
Common errors
Forgetting the decorator
class Temperature:
def is_valid(celsius):
return celsius >= -273.15
print(Temperature.is_valid(10)) # True
t = Temperature()
print(t.is_valid(10))The first call works, because access through the class returns the plain function and 10 becomes celsius. The second call fails:
TypeError: Temperature.is_valid() takes 1 positional argument but 2 were givenThrough an instance, Python binds t as the first argument, so the function receives t and 10. The confusing part is that the class-level call works, so the bug may hide until someone uses an instance. If a method has no self, it needs @staticmethod.
Adding `self` to a static method
If you write @staticmethod def is_valid(self, celsius), Python will not supply self. Callers must pass two arguments, and Temperature.is_valid(10) fails with a missing-argument TypeError. Remove self from static methods.
Needing `self` without noticing
If a static method starts to need instance data, you will find yourself passing self.something into it from every call site. That is a sign the method should be an instance method. The same applies to class data: see the previous section.
Calling through a hard-coded class name
Parser.clean(text) inside a method skips subclass overrides, as the inheritance example showed. Use self.clean(text) or cls.clean(text).
Reading the raw class dictionary
Temperature.__dict__["is_valid"] gives the staticmethod wrapper, not the function. In Python 3.10 and later the wrapper is directly callable, but in earlier versions it is not, and calling it raises TypeError: 'staticmethod' object is not callable. Use normal attribute access (Temperature.is_valid) unless you are deliberately inspecting the wrapper, and reach the function with .__func__ if you need it.
When a static method is the right choice
Use a static method when all of the following hold:
- The function does not need the instance or the class.
- It is closely tied to the class's purpose, so grouping it there helps readers.
- You want subclasses to be able to override it, or you want it reachable as
self.name(...).
Use a class method instead when the function builds instances or reads class attributes and should respect subclasses. Use an instance method when it reads or changes instance state. Use a module-level function when the logic is general or used across unrelated classes.
Exercises
Exercise
Given this class, what happens when you run Counter().step(3), and how do you fix it so that both Counter.step(3) and Counter().step(3) return 4?
class Counter:
def step(n):
return n + 1
Show answer
Called on an instance, Python passes the instance as the first argument, so step receives two arguments (the Counter and 3) and raises TypeError: Counter.step() takes 1 positional argument but 2 were given. Fix it by adding the decorator: put @staticmethod on the line above def step(n):. With the decorator, Python binds nothing, so both Counter.step(3) and Counter().step(3) return 4.
Exercise
A class Report has a static method format_row(cells) and an instance method render(self, rows) that calls Report.format_row(row) for each row. A subclass CsvReport overrides format_row, but CsvReport().render(rows) still uses the parent's version. Why, and what is the one-line change in render that fixes it?
Show answer
Report.format_row names the parent class directly, so lookup always finds the parent's version and never reaches the subclass. Change the call to self.format_row(row). Lookup then starts at the instance's class, finds CsvReport.format_row, and uses the override.