Sub topic 7
Abstract class methods and static methods
This chapter assumes you know how @abstractmethod blocks instantiation of incomplete subclasses and how @classmethod and @staticmethod behave on ordinary classes. It covers how to combine them, what the abstract check does and does not cover, and the gotchas that follow.
Why abstract class and static methods exist
Not every requirement in an interface belongs to an instance. Some belong to the class:
- Alternative constructors. A subclass must know how to build itself from a config dictionary, a file, or a string. This is a natural
@classmethod, because it receivesclsand returns an instance of the right subclass. - Class-level facts. A subclass must declare its registry name, file extension, or protocol version. These need no instance state, so a
@staticmethodfits.
If you declared these as plain abstract instance methods, callers would need an object before they could ask which file extension it handles. Combining @abstractmethod with @classmethod or @staticmethod lets the interface demand them at class level.
Decorator order
@abstractmethod must be the innermost decorator, directly above the def line. The outer decorator then wraps a function that is already marked abstract.
from abc import ABC, abstractmethod
class Reader(ABC):
@staticmethod
@abstractmethod
def extension() -> str:
"""File extension handled by this reader, such as '.csv'."""
@classmethod
@abstractmethod
def parse(cls, text: str) -> "Reader":
"""Build a reader from raw text."""
@classmethod
def supports(cls, filename: str) -> bool:
return filename.endswith(cls.extension())
class CsvReader(Reader):
def __init__(self, rows: list) -> None:
self.rows = rows
@staticmethod
def extension() -> str:
return ".csv"
@classmethod
def parse(cls, text: str) -> "CsvReader":
return cls([line.split(",") for line in text.splitlines()])
class Half(Reader):
@staticmethod
def extension() -> str:
return ".half"
print(sorted(Reader.__abstractmethods__))
print(CsvReader.supports("data.csv"))
print(CsvReader.parse("a,b\n1,2").rows)
try:
Half()
except TypeError:
print("Half is still abstract")Running it prints:
['extension', 'parse']
True
[['a', 'b'], ['1', '2']]
Half is still abstractReader.supports is a concrete class method. It calls the abstract extension through cls, so each subclass supplies its own value. This is the template method idea from earlier in the tutorial, applied at class level.
The table summarizes the valid stacks.
| Stack, outermost first | Meaning |
|---|---|
| `@classmethod`, `@abstractmethod` | Subclasses must define a class method. |
| `@staticmethod`, `@abstractmethod` | Subclasses must define a static method. |
| `@property`, `@abstractmethod` | Subclasses must define a property. |
| `@abstractmethod`, `@classmethod` | Wrong order. Do not use it. |
Older code may use abc.abstractclassmethod and abc.abstractstaticmethod. They have been deprecated since Python 3.3, so use the stacked form instead.
How the check works
The mechanism is the same as for abstract instance methods. Only the marking differs.
@abstractmethodsets__isabstractmethod__ = Trueon the function.@classmethodand@staticmethodforward that flag, so the wrapper object reports itself as abstract too.- When the class is created,
ABCMetascans the namespace and the bases. It collects every name whose value reports__isabstractmethod__into__abstractmethods__. object.__new__refuses to build an instance if__abstractmethods__is not empty.
The error message for an incomplete subclass names the missing methods, and its exact wording differs between Python versions. Catch TypeError and do not match on the text.
Gotcha: the check applies to instantiation only
Abstract class methods and static methods are the usual way to call something without an instance. That means the instantiation check never runs for them. You can call an abstract method directly on the abstract class, and its body executes.
from abc import ABC, abstractmethod
class Reader(ABC):
@staticmethod
@abstractmethod
def extension() -> str:
"""File extension handled by this reader."""
@classmethod
def supports(cls, filename: str) -> bool:
return filename.endswith(cls.extension())
print(Reader.extension())
try:
Reader.supports("data.csv")
except TypeError as exc:
print("TypeError:", exc)Reader.extension() prints None, because the body is just a docstring. Reader.supports("data.csv") then fails with a confusing TypeError from str.endswith, because None is not a valid suffix. Python never told you that Reader is abstract, because you did not instantiate it.
Two habits reduce the risk:
- Do not call class-level API on the abstract base itself. Call it on concrete subclasses.
- If the base can be reached by mistake, make the body fail loudly with
raise NotImplementedError.
Gotcha: overrides are not checked for kind
ABCMeta only checks that a name is overridden by something that is not itself abstract. It does not check that the override is also a class method or static method, and it does not check signatures.
from abc import ABC, abstractmethod
class Reader(ABC):
@staticmethod
@abstractmethod
def extension() -> str:
"""File extension handled by this reader."""
@classmethod
def supports(cls, filename: str) -> bool:
return filename.endswith(cls.extension())
class Sloppy(Reader):
def extension(self) -> str:
return ".x"
obj = Sloppy()
print(type(obj).__name__)
print(obj.extension())
try:
Sloppy.supports("a.x")
except TypeError as exc:
print("TypeError:", exc)Sloppy overrides the static method with an instance method, and Sloppy() succeeds. obj.extension() works because the instance is bound as self. But Sloppy.supports("a.x") calls cls.extension() with no instance and fails with a missing-argument TypeError. The ABC cannot catch this at runtime, so use a type checker such as mypy or pyright to verify that overrides match the declared kind and signature.
Giving an abstract class method a default body
An abstract method may contain real code. Subclasses must still override it, but they can reuse the base version through super(). This works for class methods and static methods alike, with the usual zero-argument super() in a class method.
from abc import ABC, abstractmethod
class Service(ABC):
@classmethod
@abstractmethod
def defaults(cls) -> dict:
"""Return default settings. Subclasses extend these."""
return {"timeout": 10}
class ApiService(Service):
@classmethod
def defaults(cls) -> dict:
return {**super().defaults(), "retries": 3}
print(ApiService.defaults())
try:
Service()
except TypeError:
print("Service is abstract")The output is {'timeout': 10, 'retries': 3} followed by Service is abstract. This pattern keeps shared defaults in one place while still forcing each subclass to take a position on them. It works best when the base body is small and meaningful on its own. If it is only a placeholder, use a docstring or raise NotImplementedError.
Using abstract class methods as factories
An abstract class method is a good fit for a factory that returns cls(...). Because cls is the subclass that was called, the same method builds the right type without any if chains in the caller.
from abc import ABC, abstractmethod
class Plugin(ABC):
@classmethod
@abstractmethod
def from_config(cls, config: dict) -> "Plugin":
"""Build an instance from a configuration dictionary."""
@staticmethod
@abstractmethod
def name() -> str:
"""Return the plugin's registry name."""
class EchoPlugin(Plugin):
def __init__(self, prefix: str) -> None:
self.prefix = prefix
@classmethod
def from_config(cls, config: dict) -> "EchoPlugin":
return cls(config.get("prefix", ""))
@staticmethod
def name() -> str:
return "echo"
class ShoutPlugin(EchoPlugin):
@staticmethod
def name() -> str:
return "shout"
registry = {p.name(): p for p in (EchoPlugin, ShoutPlugin)}
plugin = registry["shout"].from_config({"prefix": ">> "})
print(type(plugin).__name__, repr(plugin.prefix))This prints ShoutPlugin '>> '. ShoutPlugin inherits from_config from EchoPlugin, and cls is ShoutPlugin at the call, so the factory returns the right type without being rewritten. Because name is a static method, the registry is built from the classes themselves, with no instances needed.
Choosing between the forms
- Abstract instance method: the behavior depends on the object's state.
- Abstract class method: the behavior needs the class, for example to construct an instance or read other class-level data. It receives
cls. - Abstract static method: the behavior needs neither the class nor an instance, but you still want every subclass to define it. A fixed identifier or a constant is typical.
- Abstract property: the value is part of the instance's state or is computed from it.
If a subclass should provide a constant, a static method works but a class attribute can be simpler. The ABC cannot enforce class attributes, though. An abstract static method is the way to make a missing constant fail at instantiation.
Exercises
Exercise
You write a class method on an ABC, and its decorators from top to bottom are @abstractmethod then @classmethod. What is wrong, and what is the correct order?
Show answer
@abstractmethod must be the innermost decorator, directly above def. Applied on top of @classmethod, it is applied to the classmethod object instead of the function, which typically raises AttributeError or leaves the method not abstract. The correct order is @classmethod on top, then @abstractmethod, then def.
Exercise
A base class declares an abstract static method name(). A subclass overrides it as an instance method, def name(self). Can the subclass be instantiated, and does a call like Sub.name() work?
Show answer
Yes, the subclass can be instantiated, because ABCMeta only checks that the name is overridden by something that is not abstract. It does not check that the override is a static method. Sub.name() fails with a TypeError about a missing argument, because no instance is bound. Calling name() on an instance works. A type checker is the tool that catches this mismatch.
Exercise
Reader is an ABC with an abstract static method extension() whose body is only a docstring. Why does Reader.extension() not raise TypeError, and what does it return?
Show answer
The abstract check happens only when an instance is created. Calling a static or class method on the class itself never creates an instance, so the body runs. A body that is only a docstring returns None.