I couldn\'t find documentation on an equivalent of Java\'s final
in Python, is there such a thing?
I\'m creating a snapshot of an object (used for restorati
Python 3.8 (via PEP 591) adds Final
variables, functions, methods and classes. Here are some ways to use it:
@final
Decorator (classes, methods)
from typing import final
@final
class Base:
# Cannot inherit from Base
class Base:
@final
def foo(self):
# Cannot override foo in subclass
Final
annotation
from typing import Final
PI: Final[float] = 3.14159 # Cannot set PI to another value
KM_IN_MILES: Final = 0.621371 # Type annotation is optional
class Foo:
def __init__(self):
self.bar: Final = "baz" # Final instance attributes only allowed in __init__
Please note that like other typing hints, these do not prevent you from overriding the types, but they do help linters or IDEs warn you about incorrect type usage.