| 1 |
.. _class-basics: |
| 2 |
|
| 3 |
Class basics |
| 4 |
============ |
| 5 |
|
| 6 |
This section will help get you started annotating your |
| 7 |
classes. Built-in classes such as ``int`` also follow these same |
| 8 |
rules. |
| 9 |
|
| 10 |
Instance and class attributes |
| 11 |
***************************** |
| 12 |
|
| 13 |
The mypy type checker detects if you are trying to access a missing |
| 14 |
attribute, which is a very common programming error. For this to work |
| 15 |
correctly, instance and class attributes must be defined or |
| 16 |
initialized within the class. Mypy infers the types of attributes: |
| 17 |
|
| 18 |
.. code-block:: python |
| 19 |
|
| 20 |
class A: |
| 21 |
def __init__(self, x: int) -> None: |
| 22 |
self.x = x # Aha, attribute 'x' of type 'int' |
| 23 |
|
| 24 |
a = A(1) |
| 25 |
a.x = 2 # OK! |
| 26 |
a.y = 3 # Error: "A" has no attribute "y" |
| 27 |
|
| 28 |
This is a bit like each class having an implicitly defined |
| 29 |
:py:data:`__slots__ <object.__slots__>` attribute. This is only enforced during type |
| 30 |
checking and not when your program is running. |
| 31 |
|
| 32 |
You can declare types of variables in the class body explicitly using |
| 33 |
a type annotation: |
| 34 |
|
| 35 |
.. code-block:: python |
| 36 |
|
| 37 |
class A: |
| 38 |
x: list[int] # Declare attribute 'x' of type list[int] |
| 39 |
|
| 40 |
a = A() |
| 41 |
a.x = [1] # OK |
| 42 |
|
| 43 |
As in Python generally, a variable defined in the class body can be used |
| 44 |
as a class or an instance variable. (As discussed in the next section, you |
| 45 |
can override this with a :py:data:`~typing.ClassVar` annotation.) |
| 46 |
|
| 47 |
Similarly, you can give explicit types to instance variables defined |
| 48 |
in a method: |
| 49 |
|
| 50 |
.. code-block:: python |
| 51 |
|
| 52 |
class A: |
| 53 |
def __init__(self) -> None: |
| 54 |
self.x: list[int] = [] |
| 55 |
|
| 56 |
def f(self) -> None: |
| 57 |
self.y: Any = 0 |
| 58 |
|
| 59 |
You can only define an instance variable within a method if you assign |
| 60 |
to it explicitly using ``self``: |
| 61 |
|
| 62 |
.. code-block:: python |
| 63 |
|
| 64 |
class A: |
| 65 |
def __init__(self) -> None: |
| 66 |
self.y = 1 # Define 'y' |
| 67 |
a = self |
| 68 |
a.x = 1 # Error: 'x' not defined |
| 69 |
|
| 70 |
Annotating __init__ methods |
| 71 |
*************************** |
| 72 |
|
| 73 |
The :py:meth:`__init__ <object.__init__>` method is somewhat special -- it doesn't return a |
| 74 |
value. This is best expressed as ``-> None``. However, since many feel |
| 75 |
this is redundant, it is allowed to omit the return type declaration |
| 76 |
on :py:meth:`__init__ <object.__init__>` methods **if at least one argument is annotated**. For |
| 77 |
example, in the following classes :py:meth:`__init__ <object.__init__>` is considered fully |
| 78 |
annotated: |
| 79 |
|
| 80 |
.. code-block:: python |
| 81 |
|
| 82 |
class C1: |
| 83 |
def __init__(self) -> None: |
| 84 |
self.var = 42 |
| 85 |
|
| 86 |
class C2: |
| 87 |
def __init__(self, arg: int): |
| 88 |
self.var = arg |
| 89 |
|
| 90 |
However, if :py:meth:`__init__ <object.__init__>` has no annotated arguments and no return type |
| 91 |
annotation, it is considered an untyped method: |
| 92 |
|
| 93 |
.. code-block:: python |
| 94 |
|
| 95 |
class C3: |
| 96 |
def __init__(self): |
| 97 |
# This body is not type checked |
| 98 |
self.var = 42 + 'abc' |
| 99 |
|
| 100 |
Class attribute annotations |
| 101 |
*************************** |
| 102 |
|
| 103 |
You can use a :py:data:`ClassVar[t] <typing.ClassVar>` annotation to explicitly declare that a |
| 104 |
particular attribute should not be set on instances: |
| 105 |
|
| 106 |
.. code-block:: python |
| 107 |
|
| 108 |
from typing import ClassVar |
| 109 |
|
| 110 |
class A: |
| 111 |
x: ClassVar[int] = 0 # Class variable only |
| 112 |
|
| 113 |
A.x += 1 # OK |
| 114 |
|
| 115 |
a = A() |
| 116 |
a.x = 1 # Error: Cannot assign to class variable "x" via instance |
| 117 |
print(a.x) # OK -- can be read through an instance |
| 118 |
|
| 119 |
It's not necessary to annotate all class variables using |
| 120 |
:py:data:`~typing.ClassVar`. An attribute without the :py:data:`~typing.ClassVar` annotation can |
| 121 |
still be used as a class variable. However, mypy won't prevent it from |
| 122 |
being used as an instance variable, as discussed previously: |
| 123 |
|
| 124 |
.. code-block:: python |
| 125 |
|
| 126 |
class A: |
| 127 |
x = 0 # Can be used as a class or instance variable |
| 128 |
|
| 129 |
A.x += 1 # OK |
| 130 |
|
| 131 |
a = A() |
| 132 |
a.x = 1 # Also OK |
| 133 |
|
| 134 |
Note that :py:data:`~typing.ClassVar` is not a class, and you can't use it with |
| 135 |
:py:func:`isinstance` or :py:func:`issubclass`. It does not change Python |
| 136 |
runtime behavior -- it's only for type checkers such as mypy (and |
| 137 |
also helpful for human readers). |
| 138 |
|
| 139 |
You can also omit the square brackets and the variable type in |
| 140 |
a :py:data:`~typing.ClassVar` annotation, but this might not do what you'd expect: |
| 141 |
|
| 142 |
.. code-block:: python |
| 143 |
|
| 144 |
class A: |
| 145 |
y: ClassVar = 0 # Type implicitly Any! |
| 146 |
|
| 147 |
In this case the type of the attribute will be implicitly ``Any``. |
| 148 |
This behavior will change in the future, since it's surprising. |
| 149 |
|
| 150 |
An explicit :py:data:`~typing.ClassVar` may be particularly handy to distinguish |
| 151 |
between class and instance variables with callable types. For example: |
| 152 |
|
| 153 |
.. code-block:: python |
| 154 |
|
| 155 |
from collections.abc import Callable |
| 156 |
from typing import ClassVar |
| 157 |
|
| 158 |
class A: |
| 159 |
foo: Callable[[int], None] |
| 160 |
bar: ClassVar[Callable[[A, int], None]] |
| 161 |
bad: Callable[[A], None] |
| 162 |
|
| 163 |
A().foo(42) # OK |
| 164 |
A().bar(42) # OK |
| 165 |
A().bad() # Error: Too few arguments |
| 166 |
|
| 167 |
.. note:: |
| 168 |
A :py:data:`~typing.ClassVar` type parameter cannot include type variables: |
| 169 |
``ClassVar[T]`` and ``ClassVar[list[T]]`` |
| 170 |
are both invalid if ``T`` is a type variable (see :ref:`generic-classes` |
| 171 |
for more about type variables). |
| 172 |
|
| 173 |
Overriding statically typed methods |
| 174 |
*********************************** |
| 175 |
|
| 176 |
When overriding a statically typed method, mypy checks that the |
| 177 |
override has a compatible signature: |
| 178 |
|
| 179 |
.. code-block:: python |
| 180 |
|
| 181 |
class Base: |
| 182 |
def f(self, x: int) -> None: |
| 183 |
... |
| 184 |
|
| 185 |
class Derived1(Base): |
| 186 |
def f(self, x: str) -> None: # Error: type of 'x' incompatible |
| 187 |
... |
| 188 |
|
| 189 |
class Derived2(Base): |
| 190 |
def f(self, x: int, y: int) -> None: # Error: too many arguments |
| 191 |
... |
| 192 |
|
| 193 |
class Derived3(Base): |
| 194 |
def f(self, x: int) -> None: # OK |
| 195 |
... |
| 196 |
|
| 197 |
class Derived4(Base): |
| 198 |
def f(self, x: float) -> None: # OK: mypy treats int as a subtype of float |
| 199 |
... |
| 200 |
|
| 201 |
class Derived5(Base): |
| 202 |
def f(self, x: int, y: int = 0) -> None: # OK: accepts more than the base |
| 203 |
... # class method |
| 204 |
|
| 205 |
.. note:: |
| 206 |
|
| 207 |
You can also vary return types **covariantly** in overriding. For |
| 208 |
example, you could override the return type ``Iterable[int]`` with a |
| 209 |
subtype such as ``list[int]``. Similarly, you can vary argument types |
| 210 |
**contravariantly** -- subclasses can have more general argument types. |
| 211 |
|
| 212 |
In order to ensure that your code remains correct when renaming methods, |
| 213 |
it can be helpful to explicitly mark a method as overriding a base |
| 214 |
method. This can be done with the ``@override`` decorator. ``@override`` |
| 215 |
can be imported from ``typing`` starting with Python 3.12 or from |
| 216 |
``typing_extensions`` for use with older Python versions. If the base |
| 217 |
method is then renamed while the overriding method is not, mypy will |
| 218 |
show an error: |
| 219 |
|
| 220 |
.. code-block:: python |
| 221 |
|
| 222 |
from typing import override |
| 223 |
|
| 224 |
class Base: |
| 225 |
def f(self, x: int) -> None: |
| 226 |
... |
| 227 |
def g_renamed(self, y: str) -> None: |
| 228 |
... |
| 229 |
|
| 230 |
class Derived1(Base): |
| 231 |
@override |
| 232 |
def f(self, x: int) -> None: # OK |
| 233 |
... |
| 234 |
|
| 235 |
@override |
| 236 |
def g(self, y: str) -> None: # Error: no corresponding base method found |
| 237 |
... |
| 238 |
|
| 239 |
.. note:: |
| 240 |
|
| 241 |
Use :ref:`--enable-error-code explicit-override <code-explicit-override>` to require |
| 242 |
that method overrides use the ``@override`` decorator. Emit an error if it is missing. |
| 243 |
|
| 244 |
You can also override a statically typed method with a dynamically |
| 245 |
typed one. This allows dynamically typed code to override methods |
| 246 |
defined in library classes without worrying about their type |
| 247 |
signatures. |
| 248 |
|
| 249 |
As always, relying on dynamically typed code can be unsafe. There is no |
| 250 |
runtime enforcement that the method override returns a value that is |
| 251 |
compatible with the original return type, since annotations have no |
| 252 |
effect at runtime: |
| 253 |
|
| 254 |
.. code-block:: python |
| 255 |
|
| 256 |
class Base: |
| 257 |
def inc(self, x: int) -> int: |
| 258 |
return x + 1 |
| 259 |
|
| 260 |
class Derived(Base): |
| 261 |
def inc(self, x): # Override, dynamically typed |
| 262 |
return 'hello' # Incompatible with 'Base', but no mypy error |
| 263 |
|
| 264 |
Abstract base classes and multiple inheritance |
| 265 |
********************************************** |
| 266 |
|
| 267 |
Mypy supports Python :doc:`abstract base classes <python:library/abc>` (ABCs). Abstract classes |
| 268 |
have at least one abstract method or property that must be implemented |
| 269 |
by any *concrete* (non-abstract) subclass. You can define abstract base |
| 270 |
classes using the :py:class:`abc.ABCMeta` metaclass and the :py:func:`@abc.abstractmethod <abc.abstractmethod>` |
| 271 |
function decorator. Example: |
| 272 |
|
| 273 |
.. code-block:: python |
| 274 |
|
| 275 |
from abc import ABCMeta, abstractmethod |
| 276 |
|
| 277 |
class Animal(metaclass=ABCMeta): |
| 278 |
@abstractmethod |
| 279 |
def eat(self, food: str) -> None: pass |
| 280 |
|
| 281 |
@property |
| 282 |
@abstractmethod |
| 283 |
def can_walk(self) -> bool: pass |
| 284 |
|
| 285 |
class Cat(Animal): |
| 286 |
def eat(self, food: str) -> None: |
| 287 |
... # Body omitted |
| 288 |
|
| 289 |
@property |
| 290 |
def can_walk(self) -> bool: |
| 291 |
return True |
| 292 |
|
| 293 |
x = Animal() # Error: 'Animal' is abstract due to 'eat' and 'can_walk' |
| 294 |
y = Cat() # OK |
| 295 |
|
| 296 |
Note that mypy performs checking for unimplemented abstract methods |
| 297 |
even if you omit the :py:class:`~abc.ABCMeta` metaclass. This can be useful if the |
| 298 |
metaclass would cause runtime metaclass conflicts. |
| 299 |
|
| 300 |
Since you can't create instances of ABCs, they are most commonly used in |
| 301 |
type annotations. For example, this method accepts arbitrary iterables |
| 302 |
containing arbitrary animals (instances of concrete ``Animal`` |
| 303 |
subclasses): |
| 304 |
|
| 305 |
.. code-block:: python |
| 306 |
|
| 307 |
def feed_all(animals: Iterable[Animal], food: str) -> None: |
| 308 |
for animal in animals: |
| 309 |
animal.eat(food) |
| 310 |
|
| 311 |
There is one important peculiarity about how ABCs work in Python -- |
| 312 |
whether a particular class is abstract or not is somewhat implicit. |
| 313 |
In the example below, ``Derived`` is treated as an abstract base class |
| 314 |
since ``Derived`` inherits an abstract ``f`` method from ``Base`` and |
| 315 |
doesn't explicitly implement it. The definition of ``Derived`` |
| 316 |
generates no errors from mypy, since it's a valid ABC: |
| 317 |
|
| 318 |
.. code-block:: python |
| 319 |
|
| 320 |
from abc import ABCMeta, abstractmethod |
| 321 |
|
| 322 |
class Base(metaclass=ABCMeta): |
| 323 |
@abstractmethod |
| 324 |
def f(self, x: int) -> None: pass |
| 325 |
|
| 326 |
class Derived(Base): # No error -- Derived is implicitly abstract |
| 327 |
def g(self) -> None: |
| 328 |
... |
| 329 |
|
| 330 |
Attempting to create an instance of ``Derived`` will be rejected, |
| 331 |
however: |
| 332 |
|
| 333 |
.. code-block:: python |
| 334 |
|
| 335 |
d = Derived() # Error: 'Derived' is abstract |
| 336 |
|
| 337 |
.. note:: |
| 338 |
|
| 339 |
It's a common error to forget to implement an abstract method. |
| 340 |
As shown above, the class definition will not generate an error |
| 341 |
in this case, but any attempt to construct an instance will be |
| 342 |
flagged as an error. |
| 343 |
|
| 344 |
Mypy allows you to omit the body for an abstract method, but if you do so, |
| 345 |
it is unsafe to call such method via ``super()``. For example: |
| 346 |
|
| 347 |
.. code-block:: python |
| 348 |
|
| 349 |
from abc import abstractmethod |
| 350 |
class Base: |
| 351 |
@abstractmethod |
| 352 |
def foo(self) -> int: pass |
| 353 |
@abstractmethod |
| 354 |
def bar(self) -> int: |
| 355 |
return 0 |
| 356 |
class Sub(Base): |
| 357 |
def foo(self) -> int: |
| 358 |
return super().foo() + 1 # error: Call to abstract method "foo" of "Base" |
| 359 |
# with trivial body via super() is unsafe |
| 360 |
@abstractmethod |
| 361 |
def bar(self) -> int: |
| 362 |
return super().bar() + 1 # This is OK however. |
| 363 |
|
| 364 |
A class can inherit any number of classes, both abstract and |
| 365 |
concrete. As with normal overrides, a dynamically typed method can |
| 366 |
override or implement a statically typed method defined in any base |
| 367 |
class, including an abstract method defined in an abstract base class. |
| 368 |
|
| 369 |
You can implement an abstract property using either a normal |
| 370 |
property or an instance variable. |
| 371 |
|
| 372 |
Slots |
| 373 |
***** |
| 374 |
|
| 375 |
When a class has explicitly defined :std:term:`__slots__`, |
| 376 |
mypy will check that all attributes assigned to are members of ``__slots__``: |
| 377 |
|
| 378 |
.. code-block:: python |
| 379 |
|
| 380 |
class Album: |
| 381 |
__slots__ = ('name', 'year') |
| 382 |
|
| 383 |
def __init__(self, name: str, year: int) -> None: |
| 384 |
self.name = name |
| 385 |
self.year = year |
| 386 |
# Error: Trying to assign name "released" that is not in "__slots__" of type "Album" |
| 387 |
self.released = True |
| 388 |
|
| 389 |
my_album = Album('Songs about Python', 2021) |
| 390 |
|
| 391 |
Mypy will only check attribute assignments against ``__slots__`` when |
| 392 |
the following conditions hold: |
| 393 |
|
| 394 |
1. All base classes (except builtin ones) must have explicit |
| 395 |
``__slots__`` defined (this mirrors Python semantics). |
| 396 |
|
| 397 |
2. ``__slots__`` does not include ``__dict__``. If ``__slots__`` |
| 398 |
includes ``__dict__``, arbitrary attributes can be set, similar to |
| 399 |
when ``__slots__`` is not defined (this mirrors Python semantics). |
| 400 |
|
| 401 |
3. All values in ``__slots__`` must be string literals. |