Movatterモバイル変換


[0]ホーム

URL:


ContentsMenuExpandLight modeDark modeAuto light/dark, in light modeAuto light/dark, in dark modeSkip to content
mypy 1.19.1 documentation
Logo
mypy 1.19.1 documentation

First steps

Type system reference

Configuring and running mypy

Miscellaneous

Project Links

Back to top

The mypy command line

This section documents mypy’s command line interface. You can viewa quick summary of the available flags by runningmypy--help.

Note

Command line flags are liable to change between releases.

Specifying what to type check

By default, you can specify what code you want mypy to type checkby passing in the paths to what you want to have type checked:

$ mypy foo.py bar.py some_directory

Note that directories are checked recursively.

Mypy also lets you specify what code to type check in several otherways. A short summary of the relevant flags is included below:for full details, seeRunning mypy and managing imports.

-mMODULE,--moduleMODULE

Asks mypy to type check the provided module. This flag may berepeated multiple times.

Mypywill not recursively type check any submodules of the providedmodule.

-pPACKAGE,--packagePACKAGE

Asks mypy to type check the provided package. This flag may berepeated multiple times.

Mypywill recursively type check any submodules of the providedpackage. This flag is identical to--module apart from thisbehavior.

-cPROGRAM_TEXT,--commandPROGRAM_TEXT

Asks mypy to type check the provided string as a program.

--exclude

A regular expression that matches file names, directory names and pathswhich mypy should ignore while recursively discovering files to check.Use forward slashes on all platforms.

For instance, to avoid discovering any files namedsetup.py you couldpass--exclude'/setup\.py$'. Similarly, you can ignore discoveringdirectories with a given name by e.g.--exclude/build/ orthose matching a subpath with--exclude/project/vendor/. To ignoremultiple files / directories / paths, you can provide the –excludeflag more than once, e.g--exclude'/setup\.py$'--exclude'/build/'.

Note that this flag only affects recursive directory tree discovery, thatis, when mypy is discovering files within a directory tree or submodules ofa package to check. If you pass a file or module explicitly it will still bechecked. For instance,mypy--exclude'/setup.py$'but_still_check/setup.py.

In particular,--exclude does not affect mypy’s discovery of filesviaimport following. You can use a per-moduleignore_errors config option to silence errors from a given module,or a per-modulefollow_imports config option to additionally avoidmypy from following imports and checking code you do not wish to be checked.

Note that mypy will never recursively discover files and directories named“site-packages”, “node_modules” or “__pycache__”, or those whose name startswith a period, exactly as--exclude'/(site-packages|node_modules|__pycache__|\..*)/$' would. Mypy will alsonever recursively discover files with extensions other than.py or.pyi.

--exclude-gitignore

This flag will add everything that matches.gitignore file(s) to--exclude.

Optional arguments

-h,--help

Show help message and exit.

-v,--verbose

More verbose messages.

-V,--version

Show program’s version number and exit.

-OFORMAT,--outputFORMAT{json}

Set a custom output format.

Config file

--config-fileCONFIG_FILE

This flag makes mypy read configuration settings from the given file.

By default settings are read frommypy.ini,.mypy.ini,pyproject.toml, orsetup.cfgin the current directory. Settings override mypy’s built-in defaults andcommand line flags can override settings.

Specifying--config-file= (with no filename) will ignoreallconfig files.

SeeThe mypy configuration file for the syntax of configuration files.

--warn-unused-configs

This flag makes mypy warn about unused[mypy-<pattern>] configfile sections.(This requires turning off incremental mode using--no-incremental.)

Import discovery

The following flags customize how exactly mypy discovers and followsimports.

--explicit-package-bases

This flag tells mypy that top-level packages will be based in either thecurrent directory, or a member of theMYPYPATH environment variable ormypy_path config option. This option is only usefulin the absence of__init__.py. SeeMapping filepaths to modules for details.

--ignore-missing-imports

This flag makes mypy ignore all missing imports. It is equivalentto adding#type:ignore comments to all unresolved importswithin your codebase.

Note that this flag doesnot suppress errors about missing namesin successfully resolved modules. For example, if one has thefollowing files:

package/__init__.pypackage/mod.py

Then mypy will generate the following errors with--ignore-missing-imports:

importpackage.unknown# No error, ignoredx=package.unknown.func()# OK. 'func' is assumed to be of type 'Any'frompackageimportunknown# No error, ignoredfrompackage.modimportNonExisting# Error: Module has no attribute 'NonExisting'

For more details, seeMissing imports.

--follow-untyped-imports

This flag makes mypy analyze imports from installed packages even ifmissing apy.typed marker or stubs.

Warning

Note that analyzing all unannotated modules might result in issueswhen analyzing code not designed to be type checked and may significantlyincrease how long mypy takes to run.

--follow-imports{normal,silent,skip,error}

This flag adjusts how mypy follows imported modules that were notexplicitly passed in via the command line.

The default option isnormal: mypy will follow and type checkall modules. For more information on what the other options do,seeFollowing imports.

--python-executableEXECUTABLE

This flag will have mypy collect type information fromPEP 561compliant packages installed for the Python executableEXECUTABLE.If not provided, mypy will use PEP 561 compliant packages installed forthe Python executable running mypy.

SeeUsing installed packages for more on making PEP 561 compliant packages.

--no-site-packages

This flag will disable searching forPEP 561 compliant packages. Thiswill also disable searching for a usable Python executable.

Use this flag if mypy cannot find a Python executable for the version ofPython being checked, and you don’t need to use PEP 561 typed packages.Otherwise, use--python-executable.

--no-silence-site-packages

By default, mypy will suppress any error messages generated withinPEP 561compliant packages. Adding this flag will disable this behavior.

--fast-module-lookup

The default logic used to scan through search paths to resolve imports has aquadratic worse-case behavior in some cases, which is for instance triggeredby a large number of folders sharing a top-level namespace as in:

foo/company/foo/a.pybar/company/bar/b.pybaz/company/baz/c.py...

If you are in this situation, you can enable an experimental fast path bysetting the--fast-module-lookup option.

--no-namespace-packages

This flag disables import discovery of namespace packages (seePEP 420).In particular, this prevents discovery of packages that don’t have an__init__.py (or__init__.pyi) file.

This flag affects how mypy finds modules and packages explicitly passed onthe command line. It also affects how mypy determines fully qualified modulenames for files passed on the command line. SeeMapping file paths tomodules for details.

Platform configuration

By default, mypy will assume that you intend to run your code using the sameoperating system and Python version you are using to run mypy itself. Thefollowing flags let you modify this behavior.

For more information on how to use these flags, seePython version and system platform checks.

--python-versionX.Y

This flag will make mypy type check your code as if it wererun under Python version X.Y. Without this option, mypy will default to usingwhatever version of Python is running mypy.

This flag will attempt to find a Python executable of the correspondingversion to search forPEP 561 compliant packages. If you’d like todisable this, use the--no-site-packages flag (seeImport discovery for more details).

--platformPLATFORM

This flag will make mypy type check your code as if it wererun under the given operating system. Without this option, mypy willdefault to using whatever operating system you are currently using.

ThePLATFORM parameter may be any string supported bysys.platform.

--always-trueNAME

This flag will treat all variables namedNAME ascompile-time constants that are always true. This flag maybe repeated.

--always-falseNAME

This flag will treat all variables namedNAME ascompile-time constants that are always false. This flag maybe repeated.

Disallow dynamic typing

TheAny type is used to represent a value that has adynamic type.The--disallow-any family of flags will disallow various uses of theAny type ina module – this lets us strategically disallow the use of dynamic typing in a controlled way.

The following options are available:

--disallow-any-unimported

This flag disallows usage of types that come from unfollowed imports(such types become aliases forAny). Unfollowed imports occur eitherwhen the imported module does not exist or when--follow-imports=skipis set.

--disallow-any-expr

This flag disallows all expressions in the module that have typeAny.If an expression of typeAny appears anywhere in the modulemypy will output an error unless the expression is immediatelyused as an argument tocast() or assigned to a variable with anexplicit type annotation.

In addition, declaring a variable of typeAnyor casting to typeAny is not allowed. Note that calling functionsthat take parameters of typeAny is still allowed.

--disallow-any-decorated

This flag disallows functions that haveAny in their signatureafter decorator transformation.

--disallow-any-explicit

This flag disallows explicitAny in type positions such as typeannotations and generic type parameters.

--disallow-any-generics

This flag disallows usage of generic types that do not specify explicittype parameters. For example, you can’t use a barex:list. Instead, youmust always write something likex:list[int].

--disallow-subclassing-any

This flag reports an error whenever a class subclasses a value oftypeAny. This may occur when the base class is imported froma module that doesn’t exist (when using--ignore-missing-imports) or isignored due to--follow-imports=skip or a#type:ignore comment on theimport statement.

Since the module is silenced, the imported class is given a type ofAny.By default mypy will assume that the subclass correctly inheritedthe base class even though that may not actually be the case. Thisflag makes mypy raise an error instead.

Untyped definitions and calls

The following flags configure how mypy handles untyped functiondefinitions or calls.

--disallow-untyped-calls

This flag reports an error whenever a function with type annotationscalls a function defined without annotations.

--untyped-calls-exclude

This flag allows one to selectively disable--disallow-untyped-callsfor functions and methods defined in specific packages, modules, or classes.Note that each exclude entry acts as a prefix. For example (assuming thereare no type annotations forthird_party_lib available):

# mypy --disallow-untyped-calls#      --untyped-calls-exclude=third_party_lib.module_a#      --untyped-calls-exclude=foo.Afromthird_party_lib.module_aimportsome_funcfromthird_party_lib.module_bimportother_funcimportfoosome_func()# OK, function comes from module `third_party_lib.module_a`other_func()# E: Call to untyped function "other_func" in typed contextfoo.A().meth()# OK, method was defined in class `foo.A`foo.B().meth()# E: Call to untyped function "meth" in typed context# file foo.pyclassA:defmeth(self):passclassB:defmeth(self):pass
--disallow-untyped-defs

This flag reports an error whenever it encounters a function definitionwithout type annotations or with incomplete type annotations.(a superset of--disallow-incomplete-defs).

For example, it would report an error fordeff(a,b) anddeff(a:int,b).

--disallow-incomplete-defs

This flag reports an error whenever it encounters a partly annotatedfunction definition, while still allowing entirely unannotated definitions.

For example, it would report an error fordeff(a:int,b) but notdeff(a,b).

--check-untyped-defs

This flag is less severe than the previous two options – it type checksthe body of every function, regardless of whether it has type annotations.(By default the bodies of functions without annotations are not typechecked.)

It will assume all arguments have typeAny and always inferAnyas the return type.

--disallow-untyped-decorators

This flag reports an error whenever a function with type annotationsis decorated with a decorator without annotations.

None and Optional handling

The following flags adjust how mypy handles values of typeNone.

--implicit-optional

This flag causes mypy to treat parameters with aNonedefault value as having an implicit optional type (T|None).

For example, if this flag is set, mypy would assume that thexparameter is actually of typeint|None in the code snippet below,since the default parameter isNone:

deffoo(x:int=None)->None:print(x)

Note: This was disabled by default starting in mypy 0.980.

--no-strict-optional

This flag effectively disables checking of optionaltypes andNone values. With this option, mypy doesn’tgenerally check the use ofNone values – it is treatedas compatible with every type.

Warning

--no-strict-optional is evil. Avoid using it and definitely donot use it without understanding what it does.

Configuring warnings

The following flags enable warnings for code that is sound but ispotentially problematic or redundant in some way.

--warn-redundant-casts

This flag will make mypy report an error whenever your code usesan unnecessary cast that can safely be removed.

--warn-unused-ignores

This flag will make mypy report an error whenever your code usesa#type:ignore comment on a line that is not actuallygenerating an error message.

This flag, along with the--warn-redundant-casts flag, are bothparticularly useful when you are upgrading mypy. Previously,you may have needed to add casts or#type:ignore annotationsto work around bugs in mypy or missing stubs for 3rd party libraries.

These two flags let you discover cases where either workarounds areno longer necessary.

--no-warn-no-return

By default, mypy will generate errors when a function is missingreturn statements in some execution paths. The only exceptionsare when:

  • The function has aNone orAny return type

  • The function has an empty body and is marked as an abstract method,is in a protocol class, or is in a stub file

  • The execution path can never return; for example, if an exception

    is always raised

Passing in--no-warn-no-return will disable these errormessages in all cases.

--warn-return-any

This flag causes mypy to generate a warning when returning a valuewith typeAny from a function declared with a non-Any return type.

--warn-unreachable

This flag will make mypy report an error whenever it encounterscode determined to be unreachable or redundant after performing type analysis.This can be a helpful way of detecting certain kinds of bugs in your code.

For example, enabling this flag will make mypy report that thex>7check is redundant and that theelse block below is unreachable.

defprocess(x:int)->None:# Error: Right operand of "or" is never evaluatedifisinstance(x,int)orx>7:# Error: Unsupported operand types for + ("int" and "str")print(x+"bad")else:# Error: 'Statement is unreachable' errorprint(x+"bad")

To help prevent mypy from generating spurious warnings, the “Statement isunreachable” warning will be silenced in exactly two cases:

  1. When the unreachable statement is araise statement, is anassertFalse statement, or calls a function that has theNoReturnreturn type hint. In other words, when the unreachable statementthrows an error or terminates the program in some way.

  2. When the unreachable statement wasintentionally marked as unreachableusingPython version and system platform checks.

Note

Mypy currently cannot detect and report unreachable or redundant codeinside any functions usingType variables with value restriction.

This limitation will be removed in future releases of mypy.

--report-deprecated-as-note

If error codedeprecated is enabled, mypy emits errors if your codeimports or uses deprecated features. This flag converts such errors tonotes, causing mypy to eventually finish with a zero exit code. Featuresare considered deprecated when decorated withwarnings.deprecated.

--deprecated-calls-exclude

This flag allows one to selectively disabledeprecated warningsfor functions and methods defined in specific packages, modules, or classes.Note that each exclude entry acts as a prefix. For example (assumingfoo.A.func is deprecated):

# mypy --enable-error-code deprecated#      --deprecated-calls-exclude=foo.Aimportfoofoo.A().func()# OK, the deprecated warning is ignored# file foo.pyfromtyping_extensionsimportdeprecatedclassA:@deprecated("Use A.func2 instead")deffunc(self):pass

Miscellaneous strictness flags

This section documents any other flags that do not neatly fall under anyof the above sections.

--allow-untyped-globals

This flag causes mypy to suppress errors caused by not being able to fullyinfer the types of global and class variables.

--allow-redefinition-new

By default, mypy won’t allow a variable to be redefined with anunrelated type. Thisexperimental flag enables the redefinition ofunannotated variables with an arbitrary type. You will also need to enable--local-partial-types.Example:

defmaybe_convert(n:int,b:bool)->int|str:ifb:x=str(n)# Assign "str"else:x=n# Assign "int"# Type of "x" is "int | str" here.returnx

Without the new flag, mypy only supports inferring optional types(X|None) from multiple assignments. With this option enabled,mypy can infer arbitrary union types.

This also enables an unannotated variable to have different types in differentcode locations:

ifcheck():forxinrange(n):# Type of "x" is "int" here....else:forxin['a','b']:# Type of "x" is "str" here....

Note: We are planning to turn this flag on by default in a future mypyrelease, along with--local-partial-types.The feature is still experimental, and the semantics may still change.

--allow-redefinition

This is an older variant of--allow-redefinition-new.This flag enables redefinition of a variable with anarbitrary typein some contexts: only redefinitions within thesame block and nesting depth as the original definition are allowed.

We have no plans to remove this flag, but we expect that--allow-redefinition-newwill replace this flag for new use cases eventually.

Example where this can be useful:

defprocess(items:list[str])->None:# 'items' has type list[str]items=[item.split()foriteminitems]# 'items' now has type list[list[str]]

The variable must be used before it can be redefined:

defprocess(items:list[str])->None:items="mypy"# invalid redefinition to str because the variable hasn't been used yetprint(items)items="100"# valid, items now has type stritems=int(items)# valid, items now has type int
--local-partial-types

In mypy, the most common cases for partial types are variables initialized usingNone,but without explicitX|None annotations. By default, mypy won’t check partial typesspanning module top level or class top level. This flag changes the behavior to only allowpartial types at local level, therefore it disallows inferring variable type forNonefrom two assignments in different scopes. For example:

a=None# Need type annotation here if using --local-partial-typesb:int|None=NoneclassFoo:bar=None# Need type annotation here if using --local-partial-typesbaz:int|None=Nonedef__init__(self)->None:self.bar=1reveal_type(Foo().bar)# 'int | None' without --local-partial-types

Note: this option is always implicitly enabled in mypy daemon and will becomeenabled by default for mypy in a future release.

--no-implicit-reexport

By default, imported values to a module are treated as exported and mypy allowsother modules to import them. This flag changes the behavior to not re-export unlessthe item is imported using from-as or is included in__all__. Note this isalways treated as enabled for stub files. For example:

# This won't re-export the valuefromfooimportbar# Neither will thisfromfooimportbarasbang# This will re-export it as bar and allow other modules to import itfromfooimportbarasbar# This will also re-export barfromfooimportbar__all__=['bar']
--strict-equality

By default, mypy allows always-false comparisons like42=='no'.Use this flag to prohibit such comparisons of non-overlapping types, andsimilar identity and container checks:

items:list[int]if'some string'initems:# Error: non-overlapping container check!...text:striftext!=b'other bytes':# Error: non-overlapping equality check!...asserttextisnotNone# OK, check against None is allowed
--strict-equality-for-none

This flag extends--strict-equality for checksagainstNone:

text:strasserttextisnotNone# Error: non-overlapping identity check!

Note that--strict-equality-for-noneonly works in combination with--strict-equality.

--strict-bytes

By default, mypy treatsbytearray andmemoryview as subtypes ofbytes whichis not true at runtime. Use this flag to disable this behavior.--strict-bytes willbe enabled by default inmypy 2.0.

deff(buf:bytes)->None:assertisinstance(buf,bytes)# Raises runtime AssertionError with bytearray/memoryviewwithopen("binary_file","wb")asfp:fp.write(buf)f(bytearray(b""))# error: Argument 1 to "f" has incompatible type "bytearray"; expected "bytes"f(memoryview(b""))# error: Argument 1 to "f" has incompatible type "memoryview"; expected "bytes"# If `f` accepts any object that implements the buffer protocol, consider using:fromcollections.abcimportBuffer# "from typing_extensions" in Python 3.11 and earlierdeff(buf:Buffer)->None:withopen("binary_file","wb")asfp:fp.write(buf)f(b"")# Okf(bytearray(b""))# Okf(memoryview(b""))# Ok
--extra-checks

This flag enables additional checks that are technically correct but may beimpractical. In particular, it prohibits partial overlap inTypedDict updates,and makes arguments prepended viaConcatenate positional-only. For example:

fromtypingimportTypedDictclassFoo(TypedDict):a:intclassBar(TypedDict):a:intb:intdeftest(foo:Foo,bar:Bar)->None:# This is technically unsafe since foo can have a subtype of Foo at# runtime, where type of key "b" is incompatible with int, see belowbar.update(foo)classBad(Foo):b:strbad:Bad={"a":0,"b":"no"}test(bad,bar)

In future more checks may be added to this flag if:

  • The corresponding use cases are rare, thus not justifying a dedicatedstrictness flag.

  • The new check cannot be supported as an opt-in error code.

--strict

This flag mode enables a defined subset of optional error-checking flags.This subset primarily includes checks for inadvertent type unsoundness (i.estrict will catch type errors as long as intentional methods like type ignoreor casting were not used.)

Note: the--warn-unreachable flagis not automatically enabled by the strict flag.

The strict flag does not take precedence over other strict-related flags.Directly specifying a flag of alternate behavior will override thebehavior of strict, regardless of the order in which they are passed.You can see the list of flags enabled by strict mode in the fullmypy--help output.

Note: the exact list of flags enabled by running--strict may changeover time.

For this version of mypy, the list of flags enabled by strict is:--warn-unused-configs,--disallow-any-generics,--disallow-subclassing-any,--disallow-untyped-calls,--disallow-untyped-defs,--disallow-incomplete-defs,--check-untyped-defs,--disallow-untyped-decorators,--warn-redundant-casts,--warn-unused-ignores,--warn-return-any,--no-implicit-reexport,--strict-equality,--strict-bytes,--extra-checks

--disable-error-code

This flag allows disabling one or multiple error codes globally.SeeError codes for more information.

# no flagx='a string'x.trim()# error: "str" has no attribute "trim"  [attr-defined]# When using --disable-error-code attr-definedx='a string'x.trim()
--enable-error-code

This flag allows enabling one or multiple error codes globally.SeeError codes for more information.

Note: This flag will override disabled error codes from the--disable-error-code flag.

# When using --disable-error-code attr-definedx='a string'x.trim()# --disable-error-code attr-defined --enable-error-code attr-definedx='a string'x.trim()# error: "str" has no attribute "trim"  [attr-defined]

Configuring error messages

The following flags let you adjust how much detail mypy displaysin error messages.

--show-error-context

This flag will precede all errors with “note” messages explaining thecontext of the error. For example, consider the following program:

classTest:deffoo(self,x:int)->int:returnx+"bar"

Mypy normally displays an error message that looks like this:

main.py:3:error:Unsupportedoperandtypesfor+("int"and"str")

If we enable this flag, the error message now looks like this:

main.py: note: In member "foo" of class "Test":main.py:3: error: Unsupported operand types for + ("int" and "str")
--show-column-numbers

This flag will add column offsets to error messages.For example, the following indicates an error in line 12, column 9(note that column offsets are 0-based):

main.py:12:9:error:Unsupportedoperandtypesfor/("int"and"str")
--show-error-code-links

This flag will also display a link to error code documentation, anchored to the error code reported by mypy.The corresponding error code will be highlighted within the documentation page.If we enable this flag, the error message now looks like this:

main.py:3:error:Unsupportedoperandtypesfor-("int"and"str")[operator]main.py:3:note:See'https://mypy.rtfd.io/en/stable/_refs.html#code-operator'formoreinfo
--show-error-end

This flag will make mypy show not just that start position wherean error was detected, but also the end position of the relevant expression.This way various tools can easily highlight the whole error span. The format isfile:line:column:end_line:end_column. This option implies--show-column-numbers.

--hide-error-codes

This flag will hide the error code[<code>] from error messages. By default, the errorcode is shown after each error message:

prog.py:1:error:"str"hasnoattribute"trim"[attr-defined]

SeeError codes for more information.

--pretty

Use visually nicer output in error messages: use soft word wrap,show source code snippets, and show error location markers.

--no-color-output

This flag will disable color output in error messages, enabled by default.

--no-error-summary

This flag will disable error summary. By default mypy shows a summary lineincluding total number of errors, number of files with errors, and numberof files checked.

--show-absolute-path

Show absolute paths to files.

--soft-error-limitN

This flag will adjust the limit after which mypy will (sometimes)disable reporting most additional errors. The limit only appliesif it seems likely that most of the remaining errors will not beuseful or they may be overly noisy. IfN is negative, there isno limit. The default limit is -1.

--force-union-syntax

Always useUnion[] andOptional[] for union typesin error messages (instead of the| operator),even on Python 3.10+.

Incremental mode

By default, mypy will store type information into a cache. Mypywill use this information to avoid unnecessary recomputation whenit type checks your code again. This can help speed up the typechecking process, especially when most parts of your program havenot changed since the previous mypy run.

If you want to speed up how long it takes to recheck your codebeyond what incremental mode can offer, try running mypy indaemon mode.

--no-incremental

This flag disables incremental mode: mypy will no longer referencethe cache when re-run.

Note that mypy will still write out to the cache even whenincremental mode is disabled: see the--cache-dir flag belowfor more details.

--cache-dirDIR

By default, mypy stores all cache data inside of a folder named.mypy_cache in the current directory. This flag lets youchange this folder. This flag can also be useful for controllingcache use when usingremote caching.

This setting will override theMYPY_CACHE_DIR environmentvariable if it is set.

Mypy will also always write to the cache even when incrementalmode is disabled so it can “warm up” the cache. To disablewriting to the cache, use--cache-dir=/dev/null (UNIX)or--cache-dir=nul (Windows).

--sqlite-cache

Use anSQLite database to store the cache.

--cache-fine-grained

Include fine-grained dependency information in the cache for the mypy daemon.

--skip-version-check

By default, mypy will ignore cache data generated by a differentversion of mypy. This flag disables that behavior.

--skip-cache-mtime-checks

Skip cache internal consistency checks based on mtime.

Advanced options

The following flags are useful mostly for people who are interestedin developing or debugging mypy internals.

--pdb

This flag will invoke the Python debugger when mypy encountersa fatal error.

--show-traceback,--tb

If set, this flag will display a full traceback when mypyencounters a fatal error.

--raise-exceptions

Raise exception on fatal error.

--custom-typing-moduleMODULE

This flag lets you use a custom module as a substitute for thetyping module.

--custom-typeshed-dirDIR

This flag specifies the directory where mypy looks for standard library typeshedstubs, instead of the typeshed that ships with mypy. This isprimarily intended to make it easier to test typeshed changes beforesubmitting them upstream, but also allows you to use a forked version oftypeshed.

Note that this doesn’t affect third-party library stubs. To test third-party stubs,for example tryMYPYPATH=stubs/sixmypy....

--warn-incomplete-stub

This flag modifies both the--disallow-untyped-defs and--disallow-incomplete-defs flags so they also report errorsif stubs in typeshed are missing type annotations or has incompleteannotations. If both flags are missing,--warn-incomplete-stubalso does nothing.

This flag is mainly intended to be used by people who want contributeto typeshed and would like a convenient way to find gaps and omissions.

If you want mypy to report an error when your codebaseuses an untypedfunction, whether that function is defined in typeshed or not, use the--disallow-untyped-calls flag. SeeUntyped definitions and callsfor more details.

--shadow-fileSOURCE_FILESHADOW_FILE

When mypy is asked to type checkSOURCE_FILE, this flag makes mypyread from and type check the contents ofSHADOW_FILE instead. However,diagnostics will continue to refer toSOURCE_FILE.

Specifying this argument multiple times (--shadow-fileX1Y1--shadow-fileX2Y2)will allow mypy to perform multiple substitutions.

This allows tooling to create temporary files with helpful modificationswithout having to change the source file in place. For example, suppose wehave a pipeline that addsreveal_type for certain variables.This pipeline is run onoriginal.py to producetemp.py.Runningmypy--shadow-fileoriginal.pytemp.pyoriginal.py will thencause mypy to type check the contents oftemp.py instead oforiginal.py,but error messages will still referenceoriginal.py.

Report generation

If these flags are set, mypy will generate a report in the specifiedformat into the specified directory.

--any-exprs-reportDIR

Causes mypy to generate a text file report documenting how manyexpressions of typeAny are present within your codebase.

--cobertura-xml-reportDIR

Causes mypy to generate a Cobertura XML type checking coverage report.

To generate this report, you must either manually install thelxmllibrary or specify mypy installation with the setuptools extramypy[reports].

--html-report/--xslt-html-reportDIR

Causes mypy to generate an HTML type checking coverage report.

To generate this report, you must either manually install thelxmllibrary or specify mypy installation with the setuptools extramypy[reports].

--linecount-reportDIR

Causes mypy to generate a text file report documenting the functionsand lines that are typed and untyped within your codebase.

--linecoverage-reportDIR

Causes mypy to generate a JSON file that maps each source file’sabsolute filename to a list of line numbers that belong to typedfunctions in that file.

--lineprecision-reportDIR

Causes mypy to generate a flat text file report with per-modulestatistics of how many lines are typechecked etc.

--txt-report/--xslt-txt-reportDIR

Causes mypy to generate a text file type checking coverage report.

To generate this report, you must either manually install thelxmllibrary or specify mypy installation with the setuptools extramypy[reports].

--xml-reportDIR

Causes mypy to generate an XML type checking coverage report.

To generate this report, you must either manually install thelxmllibrary or specify mypy installation with the setuptools extramypy[reports].

Enabling incomplete/experimental features

--enable-incomplete-feature{PreciseTupleTypes,InlineTypedDict,TypeForm}

Some features may require several mypy releases to implement, for exampledue to their complexity, potential for backwards incompatibility, orambiguous semantics that would benefit from feedback from the community.You can enable such features for early preview using this flag. Note thatit is not guaranteed that all features will be ultimately enabled bydefault. Inrare cases we may decide to not go ahead with certainfeatures.

List of currently incomplete/experimental features:

  • PreciseTupleTypes: this feature will infer more precise tuple types invarious scenarios. Before variadic types were added to the Python type systembyPEP 646, it was impossible to express a type like “a tuple withat least two integers”. The best type available wastuple[int,...].Therefore, mypy applied very lenient checking for variable-length tuples.Now this type can be expressed astuple[int,int,*tuple[int,...]].For such more precise types (when explicitlydefined by a user) mypy,for example, warns about unsafe index access, and generally handles themin a type-safe manner. However, to avoid problems in existing code, mypydoes notinfer these precise types when it technically can. Here arenotable examples wherePreciseTupleTypes infers more precise types:

    numbers:tuple[int,...]more_numbers=(1,*numbers,1)reveal_type(more_numbers)# Without PreciseTupleTypes: tuple[int, ...]# With PreciseTupleTypes: tuple[int, *tuple[int, ...], int]other_numbers=(1,1)+numbersreveal_type(other_numbers)# Without PreciseTupleTypes: tuple[int, ...]# With PreciseTupleTypes: tuple[int, int, *tuple[int, ...]]iflen(numbers)>2:reveal_type(numbers)# Without PreciseTupleTypes: tuple[int, ...]# With PreciseTupleTypes: tuple[int, int, int, *tuple[int, ...]]else:reveal_type(numbers)# Without PreciseTupleTypes: tuple[int, ...]# With PreciseTupleTypes: tuple[()] | tuple[int] | tuple[int, int]
  • InlineTypedDict: this feature enables non-standard syntax for inlineTypedDicts, for example:

    deftest_values()->{"width":int,"description":str}:return{"width":42,"description":"test"}
  • TypeForm: this feature enablesTypeForm, as described inPEP 747 – Annotating Type Forms <https://peps.python.org/pep-0747/>_.

Miscellaneous

--install-types

This flag causes mypy to install known missing stub packages forthird-party libraries using pip. It will display the pip commandthat will be run, and expects a confirmation before installinganything. For security reasons, these stubs are limited to only asmall subset of manually selected packages that have beenverified by the typeshed team. These packages include only stubfiles and no executable code.

If you use this option without providing any files or modules totype check, mypy will install stub packages suggested during theprevious mypy run. If there are files or modules to type check,mypy first type checks those, and proposes to install missingstubs at the end of the run, but only if any missing modules weredetected.

Note

This is new in mypy 0.900. Previous mypy versions included aselection of third-party package stubs, instead of havingthem installed separately.

--non-interactive

When used together with--install-types, this causes mypy to install all suggested stubpackages using pip without asking for confirmation, and thencontinues to perform type checking using the installed stubs, ifsome files or modules are provided to type check.

This is implemented as up to two mypy runs internally. The first runis used to find missing stub packages, and output is shown fromthis run only if no missing stub packages were found. If missingstub packages were found, they are installed and then another runis performed.

--junit-xmlJUNIT_XML_OUTPUT_FILE

Causes mypy to generate a JUnit XML test result document withtype checking results. This can make it easier to integrate mypywith continuous integration (CI) tools.

--junit-format{global,per_file}

If –junit-xml is set, specifies format.global (default): single test with all errors;per_file: one test entry per file with failures.

--find-occurrencesCLASS.MEMBER

This flag will make mypy print out all usages of a class memberbased on static type information. This feature is experimental.

--scripts-are-modules

This flag will give command line arguments that appear to bescripts (i.e. files whose name does not end in.py)a module name derived from the script name rather than the fixedname__main__.

This lets you check more than one script in a single mypy invocation.(The default__main__ is technically more correct, but if youhave many scripts that import a large package, the behavior enabledby this flag is often more convenient.)

On this page

[8]ページ先頭

©2009-2025 Movatter.jp