| 1 |
.. _final_attrs: |
| 2 |
|
| 3 |
Final names, methods and classes |
| 4 |
================================ |
| 5 |
|
| 6 |
This section introduces these related features: |
| 7 |
|
| 8 |
1. *Final names* are variables or attributes that should not be reassigned after |
| 9 |
initialization. They are useful for declaring constants. |
| 10 |
2. *Final methods* should not be overridden in a subclass. |
| 11 |
3. *Final classes* should not be subclassed. |
| 12 |
|
| 13 |
All of these are only enforced by mypy, and only in annotated code. |
| 14 |
There is no runtime enforcement by the Python runtime. |
| 15 |
|
| 16 |
.. note:: |
| 17 |
|
| 18 |
The examples in this page import ``Final`` and ``final`` from the |
| 19 |
``typing`` module. These types were added to ``typing`` in Python 3.8, |
| 20 |
but are also available for use in Python 3.4 - 3.7 via the |
| 21 |
``typing_extensions`` package. |
| 22 |
|
| 23 |
Final names |
| 24 |
----------- |
| 25 |
|
| 26 |
You can use the ``typing.Final`` qualifier to indicate that |
| 27 |
a name or attribute should not be reassigned, redefined, or |
| 28 |
overridden. This is often useful for module and class-level |
| 29 |
constants to prevent unintended modification. Mypy will prevent |
| 30 |
further assignments to final names in type-checked code: |
| 31 |
|
| 32 |
.. code-block:: python |
| 33 |
|
| 34 |
from typing import Final |
| 35 |
|
| 36 |
RATE: Final = 3_000 |
| 37 |
|
| 38 |
class Base: |
| 39 |
DEFAULT_ID: Final = 0 |
| 40 |
|
| 41 |
RATE = 300 # Error: can't assign to final attribute |
| 42 |
Base.DEFAULT_ID = 1 # Error: can't override a final attribute |
| 43 |
|
| 44 |
Another use case for final attributes is to protect certain attributes |
| 45 |
from being overridden in a subclass: |
| 46 |
|
| 47 |
.. code-block:: python |
| 48 |
|
| 49 |
from typing import Final |
| 50 |
|
| 51 |
class Window: |
| 52 |
BORDER_WIDTH: Final = 2.5 |
| 53 |
... |
| 54 |
|
| 55 |
class ListView(Window): |
| 56 |
BORDER_WIDTH = 3 # Error: can't override a final attribute |
| 57 |
|
| 58 |
You can use :py:class:`@property <property>` to make an attribute read-only, but unlike ``Final``, |
| 59 |
it doesn't work with module attributes, and it doesn't prevent overriding in |
| 60 |
subclasses. |
| 61 |
|
| 62 |
Syntax variants |
| 63 |
*************** |
| 64 |
|
| 65 |
You can use ``Final`` in one of these forms: |
| 66 |
|
| 67 |
* You can provide an explicit type using the syntax ``Final[<type>]``. Example: |
| 68 |
|
| 69 |
.. code-block:: python |
| 70 |
|
| 71 |
ID: Final[int] = 1 |
| 72 |
|
| 73 |
Here, mypy will infer type ``int`` for ``ID``. |
| 74 |
|
| 75 |
* You can omit the type: |
| 76 |
|
| 77 |
.. code-block:: python |
| 78 |
|
| 79 |
ID: Final = 1 |
| 80 |
|
| 81 |
Here, mypy will infer type ``Literal[1]`` for ``ID``. Note that unlike for |
| 82 |
generic classes, this is *not* the same as ``Final[Any]``. |
| 83 |
|
| 84 |
* In class bodies and stub files, you can omit the right-hand side and just write |
| 85 |
``ID: Final[int]``. |
| 86 |
|
| 87 |
* Finally, you can write ``self.id: Final = 1`` (also optionally with |
| 88 |
a type in square brackets). This is allowed *only* in |
| 89 |
:py:meth:`__init__ <object.__init__>` methods so the final instance attribute is |
| 90 |
assigned only once when an instance is created. |
| 91 |
|
| 92 |
Details of using ``Final`` |
| 93 |
************************** |
| 94 |
|
| 95 |
These are the two main rules for defining a final name: |
| 96 |
|
| 97 |
* There can be *at most one* final declaration per module or class for |
| 98 |
a given attribute. There can't be separate class-level and instance-level |
| 99 |
constants with the same name. |
| 100 |
|
| 101 |
* There must be *exactly one* assignment to a final name. |
| 102 |
|
| 103 |
A final attribute declared in a class body without an initializer must |
| 104 |
be initialized in the :py:meth:`__init__ <object.__init__>` method (you can skip the |
| 105 |
initializer in stub files): |
| 106 |
|
| 107 |
.. code-block:: python |
| 108 |
|
| 109 |
class ImmutablePoint: |
| 110 |
x: Final[int] |
| 111 |
y: Final[int] # Error: final attribute without an initializer |
| 112 |
|
| 113 |
def __init__(self) -> None: |
| 114 |
self.x = 1 # Good |
| 115 |
|
| 116 |
``Final`` can only be used as the outermost type in assignments or variable |
| 117 |
annotations. Using it in any other position is an error. In particular, |
| 118 |
``Final`` can't be used in annotations for function arguments: |
| 119 |
|
| 120 |
.. code-block:: python |
| 121 |
|
| 122 |
x: list[Final[int]] = [] # Error! |
| 123 |
|
| 124 |
def fun(x: Final[list[int]]) -> None: # Error! |
| 125 |
... |
| 126 |
|
| 127 |
``Final`` and :py:data:`~typing.ClassVar` should not be used together. Mypy will infer |
| 128 |
the scope of a final declaration automatically depending on whether it was |
| 129 |
initialized in the class body or in :py:meth:`__init__ <object.__init__>`. |
| 130 |
|
| 131 |
A final attribute can't be overridden by a subclass (even with another |
| 132 |
explicit final declaration). Note, however, that a final attribute can |
| 133 |
override a read-only property: |
| 134 |
|
| 135 |
.. code-block:: python |
| 136 |
|
| 137 |
class Base: |
| 138 |
@property |
| 139 |
def ID(self) -> int: ... |
| 140 |
|
| 141 |
class Derived(Base): |
| 142 |
ID: Final = 1 # OK |
| 143 |
|
| 144 |
Declaring a name as final only guarantees that the name will not be re-bound |
| 145 |
to another value. It doesn't make the value immutable. You can use immutable ABCs |
| 146 |
and containers to prevent mutating such values: |
| 147 |
|
| 148 |
.. code-block:: python |
| 149 |
|
| 150 |
x: Final = ['a', 'b'] |
| 151 |
x.append('c') # OK |
| 152 |
|
| 153 |
y: Final[Sequence[str]] = ['a', 'b'] |
| 154 |
y.append('x') # Error: Sequence is immutable |
| 155 |
z: Final = ('a', 'b') # Also an option |
| 156 |
|
| 157 |
Final methods |
| 158 |
------------- |
| 159 |
|
| 160 |
Like with attributes, sometimes it is useful to protect a method from |
| 161 |
overriding. You can use the ``typing.final`` decorator for this purpose: |
| 162 |
|
| 163 |
.. code-block:: python |
| 164 |
|
| 165 |
from typing import final |
| 166 |
|
| 167 |
class Base: |
| 168 |
@final |
| 169 |
def common_name(self) -> None: |
| 170 |
... |
| 171 |
|
| 172 |
class Derived(Base): |
| 173 |
def common_name(self) -> None: # Error: cannot override a final method |
| 174 |
... |
| 175 |
|
| 176 |
This ``@final`` decorator can be used with instance methods, class methods, |
| 177 |
static methods, and properties. |
| 178 |
|
| 179 |
For overloaded methods, you should add ``@final`` on the implementation |
| 180 |
to make it final (or on the first overload in stubs): |
| 181 |
|
| 182 |
.. code-block:: python |
| 183 |
|
| 184 |
from typing import final, overload |
| 185 |
|
| 186 |
class Base: |
| 187 |
@overload |
| 188 |
def method(self) -> None: ... |
| 189 |
@overload |
| 190 |
def method(self, arg: int) -> int: ... |
| 191 |
@final |
| 192 |
def method(self, x=None): |
| 193 |
... |
| 194 |
|
| 195 |
Final classes |
| 196 |
------------- |
| 197 |
|
| 198 |
You can apply the ``typing.final`` decorator to a class to indicate |
| 199 |
to mypy that it should not be subclassed: |
| 200 |
|
| 201 |
.. code-block:: python |
| 202 |
|
| 203 |
from typing import final |
| 204 |
|
| 205 |
@final |
| 206 |
class Leaf: |
| 207 |
... |
| 208 |
|
| 209 |
class MyLeaf(Leaf): # Error: Leaf can't be subclassed |
| 210 |
... |
| 211 |
|
| 212 |
The decorator acts as a declaration for mypy (and as documentation for |
| 213 |
humans), but it doesn't actually prevent subclassing at runtime. |
| 214 |
|
| 215 |
Here are some situations where using a final class may be useful: |
| 216 |
|
| 217 |
* A class wasn't designed to be subclassed. Perhaps subclassing would not |
| 218 |
work as expected, or subclassing would be error-prone. |
| 219 |
* Subclassing would make code harder to understand or maintain. |
| 220 |
For example, you may want to prevent unnecessarily tight coupling between |
| 221 |
base classes and subclasses. |
| 222 |
* You want to retain the freedom to arbitrarily change the class implementation |
| 223 |
in the future, and these changes might break subclasses. |
| 224 |
|
| 225 |
An abstract class that defines at least one abstract method or |
| 226 |
property and has ``@final`` decorator will generate an error from |
| 227 |
mypy since those attributes could never be implemented. |
| 228 |
|
| 229 |
.. code-block:: python |
| 230 |
|
| 231 |
from abc import ABCMeta, abstractmethod |
| 232 |
from typing import final |
| 233 |
|
| 234 |
@final |
| 235 |
class A(metaclass=ABCMeta): # error: Final class A has abstract attributes "f" |
| 236 |
@abstractmethod |
| 237 |
def f(self, x: int) -> None: pass |