Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically generating Python type annotations?

I'm retrofitting some old Python code to add PyType annotations. I'm doing this mechanically, by adding print statements to the top of each function

def f(a, b):
    print("type a:", type(a))
    print("type b:", type(b))

and updating accordingly.

Is there anything which can help automate this process?

like image 646
Mark Harrison Avatar asked May 18 '18 17:05

Mark Harrison


1 Answers

Sure, there are some projects out there that can help out.

  • Instagram developed the MonkeyType tool to pick up runtime type information. These are output as stubs files, but you can use the tools included to apply those to your source files as inline annotations, or use the retype project to do the same.
  • Dropbox has a similar tool called pyannotate; this tool can generate either Python 2 type hint comments or annotations.

Neither project will produce perfect type hints; always take their output as a starting point, not the authoritative final annotations. Quoting the MonkeyType readme:

With MonkeyType, it's very easy to add annotations that reflect the concrete types you use at runtime, but those annotations may not always match the full intended capability of the functions. For instance, add is capable of handling many more types than just integers. Similarly, MonkeyType may generate a concrete List annotation where an abstract Sequence or Iterable would be more appropriate. MonkeyType's annotations are an informative first draft, to be checked and corrected by a developer.

But do read the Instagram engineering blog post on MonkeyType; it has been instrumental in adding type annotations to the Instagram codebase.

Disclaimer: MonkeyType and retype are both projects by colleagues at Facebook. I have not had any input in those tools myself.

like image 145
Martijn Pieters Avatar answered Oct 30 '22 03:10

Martijn Pieters