[Python-ideas] Runtime types vs static types

Ivan Levkivskyi levkivskyi at gmail.com
Sun Jul 2 07:58:41 EDT 2017

@ Koos Zevenhoven

> and there should at least *exist* a well-defined answer to whether an
object is in 'instance' of a given type. (Not sure if 'instance' should be
world used here)

Let me illustrate why being an "instance" (or any other word) does not
apply well to runtime objects. Consider a list [1, 2, 3], then is it an
"instance" of List[int]? Probably yes. Is it an "instance" of
List[Union[str, int]]? Probably also yes. However, List[int] and
List[Union[str, int]] are mutually incompatible i.e. the latter is not a
subtype of the former and the former is not a subtype of the latter. (This
is due to lists being mutable and therefore invariant in its type variable.)

The next important point is that static type checkers never decide (or at
least I have never seen this) whether a given literal (since there are no
objects before runtime) is an "instance" of a type. Static type checkers
(roughly speaking) verify that the semantics represented by an AST is
consistent with declared/inferred types.

Concerning the above example with [1, 2, 3], static type checkers can infer
List[int] for such literal, or refuse to do so and require an explicit
annotation, or a user can overrule the inference by an explicit annotation.
This decision (whether to use List[int] or any other acceptable type for
this literal) will influence type checking outcome (i.e. are there errors
or not) even _earlier_ in the program, this is something that is not
possible at runtime.

> Ignoring that *types* are also a runtime concept seems dangerous to me.

It is not ignored. Annotations are structured type metadata accessible both
at static and runtime, there is even typing_inspect module on PyPI designed
to provide some runtime introspection of types (it is at an early stage of
development) and some elements of it might end up in typing. Also checking
subtyping between two types (without mixing them with classes) at runtime
is entirely possible, but this is very complicated task with lots of corner
cases, therefore I don't think it will be in stdlib. stdlib was always kept
simple and easy to maintain.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170702/44572a14/attachment.html>

More information about the Python-ideas mailing list