@override Decorator
You're refactoring a logging system to add file-specific functionality.
You have a Logger base class and a FileLogger subclass. You need to
override the log() method to handle file-specific logging
logic. However, in your haste, you make a typo, naming the method
log_to_file()
instead of log().
Without any checks, your code will run, but the base class's log() method will be called, not your intended override. This can lead to subtle,
hard-to-debug bugs, as the parent method may not have the file-writing logic
you've implemented.
class Logger:
def log(self, message: str) -> None:
print(f"LOG: {message}")
class FileLogger(Logger):
# OOPS! Typo here: method name doesn't match base class
def log_to_file(self, message: str, filename: str) -> None:
with open(filename, 'a') as f:
f.write(f"FILE LOG: {message}\\n")
# The user's code expects FileLogger.log to be called, but it won't be!
logger = FileLogger()
logger.log("System started.")
# This will print "LOG: System started."
# NOT write to a file as intended!
The @override decorator from the typing module is
a simple yet powerful tool for preventing this exact problem. It explicitly
marks a method as an intended override of a parent class method.
If you use @override and the method doesn't actually exist in
any of the parent classes, type checkers will raise an error. This turns a
silent, insidious bug into an error that you can fix right away. By flagging
any misspellings or non-existent overrides, it encourages safer object-oriented
programming (OOP) practices by reducing accidental bugs.
Here is a fixed version of that same code:
from typing import override
class Logger:
def log(self, message: str) -> None:
print(f"LOG: {message}")
class FileLogger(Logger):
@override # This will catch the typo!
def log_to_file(self, message: str, filename: str) -> None: # Error: no matching method in parent
with open(filename, 'a') as f:
f.write(f"FILE LOG: {message}\\n")
Any popular type checker would help notice this and tell you about the error:
- mypy - Most widely used Python type checker
- pyright/Pylance - Microsoft's type checker (default in VS Code)
- Pyre - Meta's type checker
- pytype - Google's type checker
The errors would look like this:
# mypy error: Method "log_to_file" marked with @override does not override anything [misc]
# pyright/Pylance Method "log_to_file" overrides nothing
# Pyre Invalid override [40]: `log_to_file` is not defined in base classes of `FileLogger`
Any modern Python development setup with type checking enabled will catch
these @override mistakes before your code ever runs, turning silent
bugs into immediate, fixable errors.
Questions or feedback? Feel free to reach out!