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.
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.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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With