First steps
Type system reference
Configuring and running mypy
Miscellaneous
Project Links
Instead of running mypy as a command-line tool, you can also run it asa long-running daemon (server) process and use a command-line client tosend type-checking requests to the server. This way mypy can perform typechecking much faster, since program state cached from previous runs is keptin memory and doesn’t have to be read from the file system on each run.The server also uses finer-grained dependency tracking to reduce the amountof work that needs to be done.
If you have a large codebase to check, running mypy using the mypydaemon can be10 or more times faster than the regular command-linemypy tool, especially if your workflow involves running mypyrepeatedly after small edits – which is often a good idea, as this wayyou’ll find errors sooner.
Note
The command-line interface of mypy daemon may change in future mypyreleases.
Note
Each mypy daemon process supports one user and one set of source files,and it can only process one type checking request at a time. You canrun multiple mypy daemon processes to type check multiple repositories.
The client utilitydmypy is used to control the mypy daemon.Usedmypyrun--<flags><files> to type check a set of files(or directories). This will launch the daemon if it is not running.You can use almost arbitrary mypy flags after--. The daemonwill always run on the current host. Example:
dmypyrun--prog.pypkg/*.py
dmypyrun will automatically restart the daemon if theconfiguration or mypy version changes.
The initial run will process all the code and may take a while tofinish, but subsequent runs will be quick, especially if you’ve onlychanged a few files. (You can useremote cachingto speed up the initial run. The speedup can be significant ifyou have a large codebase.)
Note
Mypy 0.780 added support for following imports in dmypy (enabled bydefault). This functionality is still experimental. You can use--follow-imports=skip or--follow-imports=error to fallback to the stable functionality. SeeFollowing imports fordetails on how these work.
Note
The mypy daemon requires--local-partial-types and automatically enables it.
Whiledmypyrun is sufficient for most uses, some workflows(ones usingremote caching, perhaps),require more precise control over the lifetime of the daemon process:
dmypystop stops the daemon.
dmypystart--<flags> starts the daemon but does not check any files.You can use almost arbitrary mypy flags after--.
dmypyrestart--<flags> restarts the daemon. The flags are the sameas withdmypystart. This is equivalent to a stop command followedby a start.
Usedmypyrun--timeoutSECONDS--<flags> (orstart orrestart) to automaticallyshut down the daemon after inactivity. By default, the daemon runsuntil it’s explicitly stopped.
dmypycheck<files> checks a set of files using an alreadyrunning daemon.
dmypyrecheck checks the same set of files as the most recentcheck orrecheck command. (You can also use the--updateand--remove options to alter the set of files, and to definewhich files should be processed.)
dmypystatus checks whether a daemon is running. It prints adiagnostic and exits with0 if there is a running daemon.
Usedmypy--help for help on additional commands and command-lineoptions not discussed here, anddmypy<command>--help for help oncommand-specific options.
UseFILE as the status file for storing daemon runtime state. This isnormally a JSON file that contains information about daemon process andconnection. The default path is.dmypy.json in the current workingdirectory.
Direct daemon stdout/stderr toFILE. This is useful for debugging daemoncrashes, since the server traceback is not always printed by the client.This is available for thestart,restart, andrun commands.
Automatically shut down server afterTIMEOUT seconds of inactivity.This is available for thestart,restart, andrun commands.
Re-checkFILE, or add it to the set of files beingchecked (and check it). This option may be repeated, and it’s only available fortherecheck command. By default, mypy finds and checks all files changedsince the previous run and files that depend on them. However, if you use this option(and/or--remove), mypy assumes that only the explicitlyspecified files have changed. This is only useful tospeed up mypy if you type check a very large number of files, and use anexternal, fast file system watcher, such aswatchman orwatchdog, to determine which files got edited or deleted.Note: This option is never required and is only available forperformance tuning.
RemoveFILE from the set of files being checked. This option may berepeated. This is only available for therecheck command. See--update above for when this may be useful.Note: This option is never required and is only available for performancetuning.
Collect information about the current internal file state. This isonly available for thestatus command. This will dump JSON toFILE in the format{path:[modification_time,size,content_hash]}. This is useful for debugging the built-in filesystem watcher.Note: This is an internal flag and the format maychange.
Write performance profiling information toFILE. This is only availablefor thecheck,recheck, andrun commands.
Store all expression types in memory for future use. This is useful to speedup future calls todmypyinspect (but uses more memory). Only valid forcheck,recheck, andrun command.
The mypy daemon supports (as an experimental feature) statically inferringdraft function and method type annotations. UsedmypysuggestFUNCTION 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, themypy plugin for PyCharm),to automatically add annotations to source files, or to propose functionsignatures.
In this example, the functionformat_id() has no annotation:
defformat_id(user):returnf"User:{user}"root=format_id(0)
dmypysuggest uses call sites, return statements, and other heuristics (such aslooking for signatures in base classes) to infer thatformat_id() acceptsanint argument and returns astr. Usedmypysuggestmodule.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 someAny types.
The following flags customize various aspects of thedmypysuggestcommand.
Output the signature as JSON, so thatPyAnnotate 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"}}]
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.
Only produce suggestions that don’t containAny types. By default mypyproposes the most precise signature found, even if it containsAny types.
Only allow some fraction of types in the suggested signature to beAny types.The fraction ranges from0 (same as--no-any) to1.
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,...).
Use a dummy name instead of plainAny for types that cannotbe inferred. This may be useful to emphasize to a user that a given typecouldn’t be inferred and needs to be entered manually.
Set the maximum number of types to try for a function (default:64).
The daemon allows one to get the declared or inferred type of an expression (or otherinformation about an expression, such as known attributes or definition location)using thedmypyinspectLOCATION command. The location of the expression should bespecified in the formatpath/to/file.py:line:column[:end_line:end_column].Both line and column are 1-based. Both start and end position are inclusive.These rules match how mypy prints the error location in error messages.
If a span is given (i.e. all 4 numbers), then only an exactly matching expressionis inspected. If only a position is given (i.e. 2 numbers, line and column), mypywill inspect all expressions that include this position, starting from theinnermost one.
Consider this Python code snippet:
deffoo(x:int,longer_name:str)->None:xlonger_name
Here to find the type ofx one needs to calldmypyinspectsrc.py:2:5:2:5ordmypyinspectsrc.py:2:5. While forlonger_name one needs to calldmypyinspectsrc.py:3:5:3:15 or, for example,dmypyinspectsrc.py:3:10.Please note that this command is only valid after daemon had a successful typecheck (without parse errors), so that types are populated, e.g. usingdmypycheck. In case where multiple expressions match the provided location,their types are returned separated by a newline.
Important note: it is recommended to check files with--export-typessince otherwise most inspections will not work without--force-reload.
What kind of inspection to run for expression(s) found. Currently the supportedinspections are:
type (default): Show the best known type of a given expression.
attrs: Show which attributes are valid for an expression (e.g. forauto-completion). Format is{"Base1":["name_1","name_2",...];"Base2":...}.Names are sorted by method resolution order. If expression refers to a module,then module attributes will be under key like"<full.module.name>".
definition (experimental): Show the definition location for a nameexpression or member expression. Format ispath/to/file.py:line:column:Symbol.If multiple definitions are found (e.g. for a Union attribute), they areseparated by comma.
Increase verbosity of types string representation (can be repeated).For example, this will print fully qualified names of instance types (like"builtins.str"), instead of just a short name (like"str").
If the location is given asline:column, this will cause daemon toreturn only at mostNUM inspections of innermost expressions.Value of 0 means no limit (this is the default). For example, if one callsdmypyinspectsrc.py:4:10--limit=1 with this code
deffoo(x:int)->str:..defbar(x:str)->None:...baz:intbar(foo(baz))
This will output just one type"int" (forbaz name expression).While without the limit option, it would output all three types:"int","str", and"None".
With this option on, the daemon will prepend each inspection result withthe full span of corresponding expression, formatted as1:2:1:4->"int".This may be useful in case multiple expressions match a location.
With this option on, the daemon will prepend each inspection result withthe kind of corresponding expression, formatted asNameExpr->"int".If both this option and--include-span are on, the kind willappear first, for exampleNameExpr:1:2:1:4->"int".
This will make the daemon include attributes ofobject (excluded bydefault) in case of anatts inspection.
Include attributes valid for some of possible expression types (by defaultan intersection is returned). This is useful for union types of type variableswith values. For example, with this code:
fromtypingimportUnionclassA:x:intz:intclassB:y:intz:intvar:Union[A,B]var
The commanddmypyinspect--showattrssrc.py:10:1 will return{"A":["z"],"B":["z"]}, while with--union-attrs it will return{"A":["x","z"],"B":["y","z"]}.
Force re-parsing and re-type-checking file before inspection. By defaultthis is done only when needed (for example file was not loaded from cacheor daemon was initially run without--export-types mypy option),since reloading may be slow (up to few seconds for very large files).