简体   繁体   中英

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?

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.

If you are looking for "semi" automatic type annotations, I found https://stackoverflow.com/a/44102211/1686377 useful. Especially it's a static analyzer which won't run your code to determine types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM