1

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.

Georgy
  • 12,464
  • 7
  • 65
  • 73
BramAppel
  • 1,346
  • 1
  • 9
  • 21
  • You need `TypeVar` instead of `Union`. See here: [What's the difference between a constrained TypeVar and a Union?](https://stackoverflow.com/a/58903907/7851470) – Georgy Feb 20 '20 at 12:31

1 Answers1

2

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.

Michael0x2a
  • 58,192
  • 30
  • 175
  • 224