Automatically generating Python type annotations?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)