Static inference of annotations
The mypy daemon supports (as an experimental feature) statically inferringdraft function and method type annotations. Use dmypy suggest FUNCTION
togenerate a draft signature in the format(param_type_1, param_type_2, …) -> ret_type
(types are included for allarguments, including keyword-only arguments, args
and *
kwargs
).
This is a low-level feature intended to be used by editor integrations,IDEs, and other tools (for example, the mypy plugin for PyCharm),to automatically add annotations to source files, or to propose functionsignatures.
In this example, the function format_id()
has no annotation:
- def format_id(user):
- return "User: {}".format(user)
- root = format_id(0)
dymypy suggest
uses call sites, return statements, and other heuristics (such aslooking for signatures in base classes) to infer that format_id()
acceptsan int
argument and returns a str
. Use dmypy suggest module.format_id
toprint the suggested signature for the function.
More generally, the target function may be specified in two ways:
- By its fully qualified name, i.e.
[package.]module.[class.]function
. - By its location in a source file, i.e.
/path/to/file.py:line
. The path can beabsolute or relative, andline
can refer to any line number withinthe function body.
This command can also be used to find a more precise alternative for an existing,imprecise annotation with some Any
types.
The following flags customize various aspects of the dmypy suggest
command.
—json
- Output the signature as JSON, so that PyAnnotate can read it and addthe signature to the source file. Here is what the JSON looks like:
- [{"func_name": "example.format_id",
- "line": 1,
- "path": "/absolute/path/to/example.py",
- "samples": 0,
- "signature": {"arg_types": ["int"], "return_type": "str"}}]
—no-errors
- Only produce suggestions that cause no errors in the checked code. By default,mypy will try to find the most precise type, even if it causes some type errors.
—no-any
- Only produce suggestions that don’t contain
Any
types. By default mypyproposes the most precise signature found, even if it containsAny
types.
—flex-any
FRACTION
- Only allow some fraction of types in the suggested signature to be
Any
types.The fraction ranges from0
(same as—no-any
) to1
.
—try-text
- Try also using
unicode
whereverstr
is inferred. This flag may be usefulfor annotating Python 2/3 straddling code.
—callsites
- Only find call sites for a given function instead of suggesting a type.This will produce a list with line numbers and types of actualarguments for each call:
/path/to/file.py:line: (arg_type_1, arg_type_2, …)
.