Python's final qualifier


Python (>=3.8) tip:

You can use the final decorator to declare that a:

  1. Method should not be overridden
  2. Class should not be subclassed

You can also use the Final annotation to declare that a variable or attribute should not be reassigned, redefined, or overridden. It can be used as indicator to another developer that the given variable should be treated as a constant:

from typing import Final 

_PI: Final =  3.14

A static type check will report an error when it's violated.

https://mypy.readthedocs.io/en/stable/final_attrs.html

from typing import Final, final

# example 1


@final
class Cat:
    @final
    def meow(self):
        return "Meow"


class WildCat(Cat):
    def meow(self):
        return "Grrr"


# mypy cat.py
# error: Cannot inherit from final class "Cat"


# example 2


class Foo:
    @final
    def bar(self):
        return "baz"


def foobar():
    return "foobar"


new = Foo()
new.bar = foobar

# mypy foo.py
# error: Cannot assign to final attribute "bar"


# example 3

favorite_color: Final[str] = "red"
favorite_color = "blue"

# mypy foo.py
# error: Cannot assign to final name "favorite_color"