Q:

Why does mypy fail on this automatically annotated module by MonkeyType?

Assume the following module and script file:
mymodule.py
# Module to be annotated by MonkeyType
def add(a, b):
    return a + b

myscript.py
from mymodule import add

add(2, 3)
add('x', 'y')

Automatically annotate the module with the MonkeyType module using the Ubuntu terminal.
$ monkeytype run myscript.py
$ monkeytype apply mymodule

mymodule.py is now altered with the added annotations.
# Module annotated by monkeytype
from typing import Union

def add(a: Union[int, str], b: Union[int, str]) -> Union[int, str]:
    return a + b

But if I run mypy, the static type checker, the execution terminates with 2 errors.
Why does this occur?
$ mypy mymodule.py
mymodule.py:4: error: Unsupported operand types for + ("int" and "str")
mymodule.py:4: error: Unsupported operand types for + ("str" and "int")
mymodule.py:4: note: Both left and right operands are unions
Found 2 errors in 1 file (checked 1 source file)

btw I use arch Python 3.8.

A:

There's no guarantee that the type annotations MonkeyType will produce are necessarily correct: deducing types using runtime information is a technique that has multiple fundamental limitations.
To quote the readme:

MonkeyType’s annotations are an informative first draft, to be checked and corrected by a developer.

In this particular case, the types are incorrect because the type signature implies doing add("foo", 3) is fine even though that will end up causing a crash at runtime: you can't add strings and ints together.

