{
  "$type": "site.standard.document",
  "canonicalUrl": "https://rednafi.com/python/typing-override/",
  "description": "Catch method override errors at type-check time with Python's @override decorator from PEP 698, preventing typos and signature mismatches.",
  "path": "/python/typing-override/",
  "publishedAt": "2024-11-06T00:00:00.000Z",
  "site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
  "tags": [
    "Python",
    "TIL",
    "Typing"
  ],
  "textContent": "Although I've been using Python 3.12 in production for nearly a year, one neat feature in\nthe typing module that escaped me was the @override decorator. Proposed in [PEP 698], it's\nbeen hanging out in typing_extensions for a while. This is one of those small features you\neither don't care about or get totally psyched over. I'm definitely in the latter camp.\n\nIn languages like C#, Java, and Kotlin, explicit overriding is required. For instance, in\nJava, you use @Override to make it clear you're overriding a method in a sub class. If you\nmess up the method name or if the method doesn't exist in the superclass, the compiler\nthrows an error. Now, with Python's @override decorator, we get similar benefits - though\nonly if you're using a static type checker.\n\nHere's an example:\n\nIn this example, Cat inherits from Animal, and we intended to override the sound\nmethod. But there's a typo in the subclass method name. Running mypy will flag it:\n\nThis decorator also works with class, property, or any other methods. Observe:\n\nIf the overriding method isn't marked with @property, mypy will raise an error:\n\nThe error message could be clearer here, though. You can use @override with class methods\ntoo:\n\nIn these cases, the order of @override doesn't matter; you can put it before or after the\nproperty decorator, and it'll still work. I personally prefer keeping it as the outermost\ndecorator.\n\nI've been gradually adding the @override decorator to my code, as it not only prevents\ntypos but also alerts me if an upstream method name changes.\n\n\n\n\n[pep 698]:\n    https://peps.python.org/pep-0698/",
  "title": "Explicit method overriding with @typing.override"
}