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.

from typing import Final, final

# example 1

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

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

# mypy
# error: Cannot inherit from final class "Cat"

# example 2

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

def foobar():
    return "foobar"

new = Foo() = foobar

# mypy
# error: Cannot assign to final attribute "bar"

# example 3

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

# mypy
# error: Cannot assign to final name "favorite_color"