Sub topic 9
Common Pitfalls and How to Avoid Them
Class methods and static methods are small features, but their mistakes tend to show up far from the line that caused them. A missing decorator can fail only when the method is called through an instance. A hard-coded class name can pass every test until someone writes a subclass. This chapter collects the errors that come up most often, shows the symptom of each, and gives a fix.
This chapter assumes you can define classes and instance methods, know what self is, read @name decorator syntax, and know the difference between class attributes and instance attributes. It also assumes you have met @classmethod and @staticmethod in the earlier chapters.
Pitfall 1: Forgetting the decorator
Python does not check that a method's first parameter is named cls. The name is a convention. What a method receives depends only on the decorator wrapped around it. Without a decorator, a function defined in a class body is an instance method, and its first parameter receives the instance.
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def from_string(cls, text): # forgot @classmethod
year, month, day = map(int, text.split("-"))
return cls(year, month, day)
try:
Date.from_string("2026-11-26")
except TypeError as error:
print(error) # Date.from_string() missing 1 required positional argument: 'text'
d = Date(2026, 1, 1)
try:
d.from_string("2026-11-26")
except TypeError as error:
print(error) # 'Date' object is not callableThe two calls fail differently. Called on the class, nothing is bound, so "2026-11-26" fills cls and text is missing. Called on an instance, the instance fills cls, so cls(year, month, day) tries to call the instance itself. The exact wording of the first message varies between Python versions.
The same mistake with static methods is sneakier:
class Temperature:
def is_valid(celsius): # forgot @staticmethod
return celsius >= -273.15
print(Temperature.is_valid(10)) # True: accessed on the class, it is a plain function
t = Temperature()
try:
t.is_valid(10)
except TypeError as error:
print(error) # Temperature.is_valid() takes 1 positional argument but 2 were givenAccessed through the class, a function is just a function, so the call works. Accessed through an instance, Python binds the instance as the first argument. A test that only calls Temperature.is_valid(...) will not catch the missing decorator. Callers who use an instance will.
To avoid this, read the line above def whenever a method's first parameter is not self. Also test each class and static method through both the class and an instance.
Pitfall 2: Hard-coding the class name
Writing the class name inside a class method works until a subclass exists. The method then ignores which class it was called on.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def origin_hardcoded(cls):
return Point(0, 0)
@classmethod
def origin(cls):
return cls(0, 0)
class NamedPoint(Point):
def describe(self):
return f"point at ({self.x}, {self.y})"
print(type(NamedPoint.origin_hardcoded()).__name__) # Point
print(type(NamedPoint.origin()).__name__) # NamedPoint
print(NamedPoint.origin().describe()) # point at (0, 0)NamedPoint.origin_hardcoded() returns a plain Point. Calling .describe() on it raises AttributeError, and the error appears at the use site, not in the class method that returned the wrong type.
Inside a class method, build instances with cls(...). Reach for the class name only when you mean that exact class regardless of subclasses (see Pitfall 4).
Pitfall 3: Alternative constructors that assume one signature
A class method that calls cls(0, 0) assumes every subclass accepts the same arguments as the parent. When a subclass changes __init__, the inherited constructor breaks.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def origin(cls):
return cls(0, 0)
class LabeledPoint(Point):
def __init__(self, x, y, label):
super().__init__(x, y)
self.label = label
try:
LabeledPoint.origin()
except TypeError as error:
print(error) # LabeledPoint.__init__() missing 1 required positional argument: 'label'You have three reasonable fixes:
- Override the class method in the subclass so it supplies the extra argument.
- Give the new parameter a default value, so the parent's calls stay valid.
- Accept
*argsand**kwargsin the class method and pass them tocls(...).
class LabeledPoint(Point):
def __init__(self, x, y, label="unnamed"):
super().__init__(x, y)
self.label = label
@classmethod
def origin(cls):
return cls(0, 0, "origin")
p = LabeledPoint.origin()
print(p.x, p.y, p.label) # 0 0 originWhichever fix you pick, always construct through cls(...). Some code skips __init__ with cls.__new__(cls) and sets attributes by hand. That also skips any validation in __init__, and objects built that way can break invariants the rest of the class relies on.
Pitfall 4: Class attributes, `cls`, and the shadowing trap
A class method can read and write class attributes through cls. Under inheritance, one operator behaves in a way that surprises many people: +=.
class Counter:
count = 0
@classmethod
def increment(cls):
cls.count += 1
return cls.count
class SubCounter(Counter):
pass
Counter.increment()
SubCounter.increment()
print(Counter.count) # 1
print(SubCounter.count) # 2
Counter.increment()
print(Counter.count) # 2
print(SubCounter.count) # 2cls.count += 1 means cls.count = cls.count + 1. When cls is SubCounter, the right side finds count on the parent through normal lookup, and it reads 1. The assignment on the left always writes to cls itself, so it creates a new count on SubCounter. From then on, SubCounter has its own counter, and later increments of Counter no longer reach it.
Mutating a shared object does not rebind anything, so it behaves differently:
class Registry:
items = []
@classmethod
def register(cls, name):
cls.items.append(name)
class PluginRegistry(Registry):
pass
Registry.register("a")
PluginRegistry.register("b")
print(Registry.items) # ['a', 'b']
print(PluginRegistry.items) # ['a', 'b']
print(PluginRegistry.items is Registry.items) # Trueappend changes the one list that both classes find. Decide which behavior you want:
| You want | Do this |
|---|---|
| One value shared by the whole class hierarchy | Write `Counter.count += 1` with the explicit base class name, or mutate a shared object |
| A separate value per subclass | Give each subclass its own attribute, or create it lazily in the class method |
| Per-instance state | Use an instance attribute set in `__init__` |
Writing Counter.count on purpose is the one case where hard-coding a class name is correct. Add a comment saying the sharing is deliberate.
Mutable class attributes carry a second risk. Test suites that call a class method which changes class state leak that state between tests unless each test resets it. Threads that call such a method can also interleave updates.
Pitfall 5: Using a static method when the method needs class data
A static method receives no class, so the only way it can read class data is to name the class. That name is fixed, and subclasses cannot change what it points to.
class Account:
MIN_BALANCE = 0
@staticmethod
def is_allowed_static(balance):
return balance >= Account.MIN_BALANCE
@classmethod
def is_allowed(cls, balance):
return balance >= cls.MIN_BALANCE
class OverdraftAccount(Account):
MIN_BALANCE = -500
print(OverdraftAccount.is_allowed_static(-100)) # False
print(OverdraftAccount.is_allowed(-100)) # TrueThe static version always checks against Account.MIN_BALANCE, so the subclass's override is invisible to it. The decision rule is short. If a method reads or writes anything that a subclass might override, make it a class method. If it reads nothing from the class or instance, a static method is fine.
The opposite mistake is making a method a class method when it never uses cls. That is harmless at runtime but misleading, because readers will look for what the class is used for. Linters such as pylint flag unused cls and unused self arguments, so enabling those checks catches both.
Pitfall 6: Stacking decorators in the wrong order
Decorators apply from the bottom up, so the one nearest def runs first. Two combinations matter in practice.
For abstract class methods, @classmethod must be the outermost decorator:
from abc import ABC, abstractmethod
class Parser(ABC):
@classmethod
@abstractmethod
def parse(cls, text):
"""Return a parsed value."""
class UpperParser(Parser):
@classmethod
def parse(cls, text):
return text.upper()
print(UpperParser.parse("abc")) # ABC
try:
Parser()
except TypeError:
print("cannot instantiate an abstract class")The Python documentation shows this order, with @abstractmethod as the innermost decorator, and you should follow it.
Combining @classmethod with @property to make a "class property" is the other trap. Python 3.9 allowed chaining them, Python 3.11 deprecated it, and Python 3.13 removed it. Code that relies on chaining fails on current versions. For a computed value that belongs to the class, a plain class method such as Config.default() is clearer. For a real class-level property, you need a custom descriptor or a metaclass, which is a separate topic.
Pitfall 7: Calling a static method inside the class body
While the class body is still running, the name of a static method refers to the staticmethod wrapper object, not to a bound function. Before Python 3.10, those wrapper objects were not callable.
class Config:
@staticmethod
def default_port():
return 8080
PORT = default_port() # works on Python 3.10 and later; TypeError before that
print(Config.PORT) # 8080If your code must run on older versions, compute the value in a module-level function or in a class method called after the class exists. The same wrapper explains why Temperature.__dict__["is_valid"] shows a staticmethod object, as you saw in the chapter on static methods.
Pitfall 8: Treating a static method as a default home for functions
A static method is an ordinary function that lives in a class namespace. It has no access to the class or instance, so putting it there is purely an organizational choice. Python does not need a class around every helper.
Ask these questions before writing @staticmethod:
- Is the function meaningful only in the context of this class, so that
Temperature.is_validreads better thanis_valid_temperature? If so, a static method is reasonable. - Is it a general helper used by other modules? A module-level function is simpler to import and test.
- Would a subclass ever want to change its behavior? If so, it should be a class or instance method so that overriding works through
clsorself.
Calling a class or static method through an instance is legal, but it can mislead readers. In report.from_string(text), the object report plays no part. Python looks up from_string and binds the class, not the instance. Prefer Report.from_string(text), which tells the reader what really happens.
Diagnosing a bug from its symptom
The diagram below walks from the symptom you see to the pitfall most likely behind it.
The same information as a lookup table:
| Symptom | Likely cause | Fix |
|---|---|---|
| `missing 1 required positional argument` when called on the class | Missing `@classmethod` | Add the decorator |
| `'X' object is not callable` inside a "class method" | Missing `@classmethod`, called on an instance | Add the decorator |
| `takes 1 positional argument but 2 were given` only via an instance | Missing `@staticmethod` | Add the decorator |
| Subclass call returns a parent instance | Hard-coded class name | Use `cls(...)` |
| `TypeError` in `__init__` only for one subclass | Constructor signature differs | Override the class method or add defaults |
| Subclass count diverges from the parent's | `cls.attr += 1` created a shadow attribute | Decide on shared or per-class state |
| Subclass override ignored by a utility | Static method reads `Base.ATTR` | Make it a class method |
| Class property fails on a newer Python | Chained `@classmethod` and `@property` | Use a plain class method or a descriptor |
A pre-merge checklist
Run through these points when you review code that uses class or static methods:
- Every method whose first parameter is
clshas@classmethoddirectly above it, and every method with noselforclshas@staticmethod. - Class methods create objects with
cls(...), not with a class name. - Each class method that constructs an object has been called on a subclass in at least one test.
- Class attribute updates are either deliberate shared state, written with the base class name, or deliberate per-class state.
- No static method reads class attributes that a subclass could override.
- Abstract class methods put
@classmethodoutermost. - Calls use the class (
Report.from_string), not an instance, unless the instance is the point.
Exercise
In the class below, Counter.increment() is called once and then Child.increment() is called once. What are the values of Counter.count and Child.count afterward, and why? class Counter: count = 0, with @classmethod def increment(cls): cls.count += 1, and class Child(Counter): pass.
Show answer
Counter.count is 1 and Child.count is 2. The first call sets Counter.count to 1. In the second call, cls is Child, so cls.count += 1 reads the inherited value 1 from Counter, then assigns 2 to a new attribute on Child, which shadows the parent's. The two counters are separate from then on. To keep one shared counter, write Counter.count += 1 inside the method.
Exercise
A class Report has def from_file(cls, path): return cls(open(path).read()) with no decorator. What error do you get from Report.from_file("a.txt"), and what error do you get from Report("x").from_file("a.txt")? Fix the class.
Show answer
Called on the class, Python binds nothing, so "a.txt" fills cls and path is missing, which raises a TypeError about a missing positional argument. Called on an instance, the instance fills cls, and cls(...) calls the instance, which raises a TypeError saying the object is not callable. Adding @classmethod above def from_file fixes both calls.
Exercise
A class Shape has a static method describe() that returns "A shape named " + Shape.NAME. A subclass Circle sets NAME = "circle", but Circle.describe() still reports the base name. Why does this happen, and how do you fix it?
Show answer
A static method receives neither the class nor the instance, so it can only use the name Shape, which always refers to the base class. Changing it to a class method, @classmethod def describe(cls): return "A shape named " + cls.NAME, makes Circle.describe() use Circle.NAME.