3.7. Typing Final
Since Python 3.8: PEP 591 -- Adding a final qualifier to typing
There is no runtime checking of these properties
3.7.1. Final Class
The following code demonstrates how to use @final decorator to mark
class as final:
>>> from typing import final
>>>
>>> @final
... class User:
... pass
>>>
>>> class Admin(User): # error
... pass
The code above will yield with an error: 'User' is decorated as '@final' and should not be subclassed.
3.7.2. Final Method
Since Python 3.8: PEP 591 -- Adding a final qualifier to typing
There is no runtime checking of these properties
The following code demonstrates how to use @final decorator to mark
method as final:
>>> from typing import final
>>>
>>> class User:
... @final
... def login(self):
... pass
>>>
>>> class Admin(User):
... def login(self): # error
... pass
The code above will yield with an error: 'User.login' is decorated as '@final' and should not be overridden:
3.7.3. Final Attribute
A special typing construct to indicate to type checkers that a name cannot be re-assigned or overridden in a subclass
There is no runtime checking of these properties
The following code demonstrates how to use Final class to mark
attribute as final:
>>> from typing import Final
>>>
>>> class User:
... username: Final[str]
... password: str
...
... def __init__(self, username, password):
... self.username = username
... self.password = password
...
... def change_password(self, new_password):
... self.password = new_password
The following code will yield with an error: 'Final' name should be initialized with a value:
>>> class User:
... username: Final[str]
... password: str