Debian Codegraph @

docs/source/dynamic_typing.rst

raw
1 .. _dynamic-typing:
2
3 Dynamically typed code
4 ======================
5
6 In :ref:`getting-started-dynamic-vs-static`, we discussed how bodies of functions
7 that don't have any explicit type annotations in their function are "dynamically typed"
8 and that mypy will not check them. In this section, we'll talk a little bit more
9 about what that means and how you can enable dynamic typing on a more fine grained basis.
10
11 In cases where your code is too magical for mypy to understand, you can make a
12 variable or parameter dynamically typed by explicitly giving it the type
13 ``Any``. Mypy will let you do basically anything with a value of type ``Any``,
14 including assigning a value of type ``Any`` to a variable of any type (or vice
15 versa).
16
17 .. code-block:: python
18
19 from typing import Any
20
21 num = 1 # Statically typed (inferred to be int)
22 num = 'x' # error: Incompatible types in assignment (expression has type "str", variable has type "int")
23
24 dyn: Any = 1 # Dynamically typed (type Any)
25 dyn = 'x' # OK
26
27 num = dyn # No error, mypy will let you assign a value of type Any to any variable
28 num += 1 # Oops, mypy still thinks num is an int
29
30 You can think of ``Any`` as a way to locally disable type checking.
31 See :ref:`silencing-type-errors` for other ways you can shut up
32 the type checker.
33
34 Operations on Any values
35 ------------------------
36
37 You can do anything using a value with type ``Any``, and the type checker
38 will not complain:
39
40 .. code-block:: python
41
42 def f(x: Any) -> int:
43 # All of these are valid!
44 x.foobar(1, y=2)
45 print(x[3] + 'f')
46 if x:
47 x.z = x(2)
48 open(x).read()
49 return x
50
51 Values derived from an ``Any`` value also usually have the type ``Any``
52 implicitly, as mypy can't infer a more precise result type. For
53 example, if you get the attribute of an ``Any`` value or call a
54 ``Any`` value the result is ``Any``:
55
56 .. code-block:: python
57
58 def f(x: Any) -> None:
59 y = x.foo()
60 reveal_type(y) # Revealed type is "Any"
61 z = y.bar("mypy will let you do anything to y")
62 reveal_type(z) # Revealed type is "Any"
63
64 ``Any`` types may propagate through your program, making type checking
65 less effective, unless you are careful.
66
67 Function parameters without annotations are also implicitly ``Any``:
68
69 .. code-block:: python
70
71 def f(x) -> None:
72 reveal_type(x) # Revealed type is "Any"
73 x.can.do["anything", x]("wants", 2)
74
75 You can make mypy warn you about untyped function parameters using the
76 :option:`--disallow-untyped-defs <mypy --disallow-untyped-defs>` flag.
77
78 Generic types missing type parameters will have those parameters implicitly
79 treated as ``Any``:
80
81 .. code-block:: python
82
83 def f(x: list) -> None:
84 reveal_type(x) # Revealed type is "builtins.list[Any]"
85 reveal_type(x[0]) # Revealed type is "Any"
86 x[0].anything_goes() # OK
87
88 You can make mypy warn you about missing generic parameters using the
89 :option:`--disallow-any-generics <mypy --disallow-any-generics>` flag.
90
91 Finally, another major source of ``Any`` types leaking into your program is from
92 third party libraries that mypy does not know about. This is particularly the case
93 when using the :option:`--ignore-missing-imports <mypy --ignore-missing-imports>`
94 flag. See :ref:`fix-missing-imports` for more information about this.
95
96 .. _any-vs-object:
97
98 Any vs. object
99 --------------
100
101 The type :py:class:`object` is another type that can have an instance of arbitrary
102 type as a value. Unlike ``Any``, :py:class:`object` is an ordinary static type (it
103 is similar to ``Object`` in Java), and only operations valid for *all*
104 types are accepted for :py:class:`object` values. These are all valid:
105
106 .. code-block:: python
107
108 def f(o: object) -> None:
109 if o:
110 print(o)
111 print(isinstance(o, int))
112 o = 2
113 o = 'foo'
114
115 These are, however, flagged as errors, since not all objects support these
116 operations:
117
118 .. code-block:: python
119
120 def f(o: object) -> None:
121 o.foo() # Error!
122 o + 2 # Error!
123 open(o) # Error!
124 n: int = 1
125 n = o # Error!
126
127
128 If you're not sure whether you need to use :py:class:`object` or ``Any``, use
129 :py:class:`object` -- only switch to using ``Any`` if you get a type checker
130 complaint.
131
132 You can use different :ref:`type narrowing <type-narrowing>`
133 techniques to narrow :py:class:`object` to a more specific
134 type (subtype) such as ``int``. Type narrowing is not needed with
135 dynamically typed values (values with type ``Any``).