Skip to content

mypy

GitHub stars GitHub release (latest SemVer) GitHub last commit GitHub commit activity GitHub contributors

Optional static typing checks for python

If you don't use python static typing, you should disable this linter by adding PYTHON_MYPY in DISABLE_LINTERS variable in your .mega-linter.yml config file

mypy documentation

mypy - GitHub

Configuration in MegaLinter

Variable Description Default value
PYTHON_MYPY_ARGUMENTS User custom arguments to add in linter CLI call
Ex: -s --foo "bar"
PYTHON_MYPY_COMMAND_REMOVE_ARGUMENTS User custom arguments to remove from command line before calling the linter
Ex: -s --foo "bar"
PYTHON_MYPY_FILTER_REGEX_INCLUDE Custom regex including filter
Ex: (src\|lib)
Include every file
PYTHON_MYPY_FILTER_REGEX_EXCLUDE Custom regex excluding filter
Ex: (test\|examples)
Exclude no file
PYTHON_MYPY_CLI_LINT_MODE Override default CLI lint mode
- file: Calls the linter for each file
- list_of_files: Call the linter with the list of files as argument
- project: Call the linter from the root of the project
list_of_files
PYTHON_MYPY_FILE_EXTENSIONS Allowed file extensions. "*" matches any extension, "" matches empty extension. Empty list excludes all files
Ex: [".py", ""]
[".py"]
PYTHON_MYPY_FILE_NAMES_REGEX File name regex filters. Regular expression list for filtering files by their base names using regex full match. Empty list includes all files
Ex: ["Dockerfile(-.+)?", "Jenkinsfile"]
Include every file
PYTHON_MYPY_PRE_COMMANDS List of bash commands to run before the linter None
PYTHON_MYPY_POST_COMMANDS List of bash commands to run after the linter None
PYTHON_MYPY_UNSECURED_ENV_VARIABLES List of env variables explicitly not filtered before calling PYTHON_MYPY and its pre/post commands None
PYTHON_MYPY_CONFIG_FILE mypy configuration file nameUse LINTER_DEFAULT to let the linter find it .mypy.ini
PYTHON_MYPY_RULES_PATH Path where to find linter configuration file Workspace folder, then MegaLinter default rules
PYTHON_MYPY_DISABLE_ERRORS Run linter but consider errors as warnings false
PYTHON_MYPY_DISABLE_ERRORS_IF_LESS_THAN Maximum number of errors allowed 0
PYTHON_MYPY_CLI_EXECUTABLE Override CLI executable ['mypy']

IDE Integration

Use mypy in your favorite IDE to catch errors before MegaLinter !

IDE Extension Name Install
Atom linter-mypy Visit Web Site
Emacs Flycheck mypy Visit Web Site
IDEA mypy-official Visit Web Site
Sublime Text SublimeLinter-contrib-mypy Visit Web Site
vim Ale Visit Web Site
vim Syntastic Visit Web Site
Visual Studio Code Mypy Install in VSCode

MegaLinter Flavours

This linter is available in the following flavours

Flavor Description Embedded linters Info
all Default MegaLinter Flavor 121 Docker Image Size (tag) Docker Pulls
cupcake MegaLinter for the most commonly used languages 83 Docker Image Size (tag) Docker Pulls
python Optimized for PYTHON based projects 61 Docker Image Size (tag) Docker Pulls

Behind the scenes

How are identified applicable files

  • File extensions: .py

How the linting is performed

  • mypy is called once with the list of files as arguments (list_of_files CLI lint mode)

Example calls

mypy myfile.py
mypy --config-file .mypy.yml myfile.py

Help content

usage: mypy [-h] [-v] [-V] [more options; see below]
            [-m MODULE] [-p PACKAGE] [-c PROGRAM_TEXT] [files ...]

Mypy is a program that will type check your Python code.

Pass in any files or folders you want to type check. Mypy will
recursively traverse any provided folders to find .py files:

    $ mypy my_program.py my_src_folder

For more information on getting started, see:

- https://mypy.readthedocs.io/en/stable/getting_started.html

For more details on both running mypy and using the flags below, see:

- https://mypy.readthedocs.io/en/stable/running_mypy.html
- https://mypy.readthedocs.io/en/stable/command_line.html

You can also use a config file to configure mypy instead of using
command line flags. For more details, see:

- https://mypy.readthedocs.io/en/stable/config_file.html

options:
  --enable-incomplete-feature FEATURE
                            Enable support of incomplete/experimental features
                            for early preview

Optional arguments:
  -h, --help                Show this help message and exit
  -v, --verbose             More verbose messages
  -V, --version             Show program's version number and exit

Config file:
  Use a config file instead of command line arguments. This is useful if you
  are using many flags or want to set different options per each module.

  --config-file CONFIG_FILE
                            Configuration file, must have a [mypy] section
                            (defaults to mypy.ini, .mypy.ini, pyproject.toml,
                            setup.cfg, ~/.config/mypy/config, ~/.mypy.ini)
  --warn-unused-configs     Warn about unused '[mypy-<pattern>]' or
                            '[[tool.mypy.overrides]]' config sections
                            (inverse: --no-warn-unused-configs)

Import discovery:
  Configure how imports are discovered and followed.

  --no-namespace-packages   Support namespace packages (PEP 420, __init__.py-
                            less) (inverse: --namespace-packages)
  --ignore-missing-imports  Silently ignore imports of missing modules
  --follow-imports {normal,silent,skip,error}
                            How to treat imports (default normal)
  --python-executable EXECUTABLE
                            Python executable used for finding PEP 561
                            compliant installed packages and stubs
  --no-site-packages        Do not search for installed PEP 561 compliant
                            packages
  --no-silence-site-packages
                            Do not silence errors in PEP 561 compliant
                            installed packages
  --junit-format {global,per_file}
                            If --junit-xml is set, specifies format. global:
                            single test with all errors; per_file: one test
                            entry per file with failures

Platform configuration:
  Type check code assuming it will be run under certain runtime conditions.
  By default, mypy assumes your code will be run using the same operating
  system and Python version you are using to run mypy itself.

  --python-version x.y      Type check code assuming it will be running on
                            Python x.y
  --platform PLATFORM       Type check special-cased code for the given OS
                            platform (defaults to sys.platform)
  --always-true NAME        Additional variable to be considered True (may be
                            repeated)
  --always-false NAME       Additional variable to be considered False (may be
                            repeated)

Disallow dynamic typing:
  Disallow the use of the dynamic 'Any' type under certain conditions.

  --disallow-any-unimported
                            Disallow Any types resulting from unfollowed
                            imports
  --disallow-any-expr       Disallow all expressions that have type Any
  --disallow-any-decorated  Disallow functions that have Any in their
                            signature after decorator transformation
  --disallow-any-explicit   Disallow explicit Any in type positions
  --disallow-any-generics   Disallow usage of generic types that do not
                            specify explicit type parameters (inverse:
                            --allow-any-generics)
  --disallow-subclassing-any
                            Disallow subclassing values of type 'Any' when
                            defining classes (inverse: --allow-subclassing-
                            any)

Untyped definitions and calls:
  Configure how untyped definitions and calls are handled. Note: by default,
  mypy ignores any untyped function definitions and assumes any calls to
  such functions have a return type of 'Any'.

  --disallow-untyped-calls  Disallow calling functions without type
                            annotations from functions with type annotations
                            (inverse: --allow-untyped-calls)
  --untyped-calls-exclude MODULE
                            Disable --disallow-untyped-calls for
                            functions/methods coming from specific package,
                            module, or class
  --disallow-untyped-defs   Disallow defining functions without type
                            annotations or with incomplete type annotations
                            (inverse: --allow-untyped-defs)
  --disallow-incomplete-defs
                            Disallow defining functions with incomplete type
                            annotations (while still allowing entirely
                            unannotated definitions) (inverse: --allow-
                            incomplete-defs)
  --check-untyped-defs      Type check the interior of functions without type
                            annotations (inverse: --no-check-untyped-defs)
  --disallow-untyped-decorators
                            Disallow decorating typed functions with untyped
                            decorators (inverse: --allow-untyped-decorators)

None and Optional handling:
  Adjust how values of type 'None' are handled. For more context on how mypy
  handles values of type 'None', see:
  https://mypy.readthedocs.io/en/stable/kinds_of_types.html#no-strict-
  optional

  --implicit-optional       Assume arguments with default values of None are
                            Optional (inverse: --no-implicit-optional)
  --no-strict-optional      Disable strict Optional checks (inverse: --strict-
                            optional)

Configuring warnings:
  Detect code that is sound but redundant or problematic.

  --warn-redundant-casts    Warn about casting an expression to its inferred
                            type (inverse: --no-warn-redundant-casts)
  --warn-unused-ignores     Warn about unneeded '# type: ignore' comments
                            (inverse: --no-warn-unused-ignores)
  --no-warn-no-return       Do not warn about functions that end without
                            returning (inverse: --warn-no-return)
  --warn-return-any         Warn about returning values of type Any from non-
                            Any typed functions (inverse: --no-warn-return-
                            any)
  --warn-unreachable        Warn about statements or expressions inferred to
                            be unreachable (inverse: --no-warn-unreachable)

Miscellaneous strictness flags:
  --allow-untyped-globals   Suppress toplevel errors caused by missing
                            annotations (inverse: --disallow-untyped-globals)
  --allow-redefinition      Allow unconditional variable redefinition with a
                            new type (inverse: --disallow-redefinition)
  --no-implicit-reexport    Treat imports as private unless aliased (inverse:
                            --implicit-reexport)
  --strict-equality         Prohibit equality, identity, and container checks
                            for non-overlapping types (inverse: --no-strict-
                            equality)
  --extra-checks            Enable additional checks that are technically
                            correct but may be impractical in real code. For
                            example, this prohibits partial overlap in
                            TypedDict updates, and makes arguments prepended
                            via Concatenate positional-only (inverse: --no-
                            extra-checks)
  --strict                  Strict mode; enables the following flags: --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, --extra-
                            checks
  --disable-error-code NAME
                            Disable a specific error code
  --enable-error-code NAME  Enable a specific error code

Configuring error messages:
  Adjust the amount of detail shown in error messages.

  --show-error-context      Precede errors with "note:" messages explaining
                            context (inverse: --hide-error-context)
  --show-column-numbers     Show column numbers in error messages (inverse:
                            --hide-column-numbers)
  --show-error-end          Show end line/end column numbers in error
                            messages. This implies --show-column-numbers
                            (inverse: --hide-error-end)
  --hide-error-codes        Hide error codes in error messages (inverse:
                            --show-error-codes)
  --show-error-code-links   Show links to error code documentation (inverse:
                            --hide-error-code-links)
  --pretty                  Use visually nicer output in error messages: Use
                            soft word wrap, show source code snippets, and
                            show error location markers (inverse: --no-pretty)
  --no-color-output         Do not colorize error messages (inverse: --color-
                            output)
  --no-error-summary        Do not show error stats summary (inverse: --error-
                            summary)
  --show-absolute-path      Show absolute paths to files (inverse: --hide-
                            absolute-path)

Incremental mode:
  Adjust how mypy incrementally type checks and caches modules. Mypy caches
  type information about modules into a cache to let you speed up future
  invocations of mypy. Also see mypy's daemon mode:
  mypy.readthedocs.io/en/stable/mypy_daemon.html#mypy-daemon

  --no-incremental          Disable module cache (inverse: --incremental)
  --cache-dir DIR           Store module cache info in the given folder in
                            incremental mode (defaults to '.mypy_cache')
  --sqlite-cache            Use a sqlite database to store the cache (inverse:
                            --no-sqlite-cache)
  --cache-fine-grained      Include fine-grained dependency information in the
                            cache for the mypy daemon
  --skip-version-check      Allow using cache written by older mypy version
  --skip-cache-mtime-checks
                            Skip cache internal consistency checks based on
                            mtime

Advanced options:
  Debug and customize mypy internals.

  --pdb                     Invoke pdb on fatal error
  --show-traceback, --tb    Show traceback on fatal error
  --raise-exceptions        Raise exception on fatal error
  --custom-typing-module MODULE
                            Use a custom typing module
  --old-type-inference      Disable new experimental type inference algorithm
  --custom-typeshed-dir DIR
                            Use the custom typeshed in DIR
  --warn-incomplete-stub    Warn if missing type annotation in typeshed, only
                            relevant with --disallow-untyped-defs or
                            --disallow-incomplete-defs enabled (inverse: --no-
                            warn-incomplete-stub)
  --shadow-file SOURCE_FILE SHADOW_FILE
                            When encountering SOURCE_FILE, read and type check
                            the contents of SHADOW_FILE instead.

Report generation:
  Generate a report in the specified format.

  --any-exprs-report DIR
  --cobertura-xml-report DIR
  --html-report DIR
  --linecount-report DIR
  --linecoverage-report DIR
  --lineprecision-report DIR
  --txt-report DIR
  --xml-report DIR
  --xslt-html-report DIR
  --xslt-txt-report DIR

Miscellaneous:
  --junit-xml JUNIT_XML     Write junit.xml to the given file
  --find-occurrences CLASS.MEMBER
                            Print out all usages of a class member
                            (experimental)
  --scripts-are-modules     Script x becomes module x instead of __main__
  --install-types           Install detected missing library stub packages
                            using pip (inverse: --no-install-types)
  --non-interactive         Install stubs without asking for confirmation and
                            hide errors, with --install-types (inverse:
                            --interactive)

Running code:
  Specify the code you want to type check. For more details, see
  mypy.readthedocs.io/en/stable/running_mypy.html#running-mypy

  --explicit-package-bases  Use current directory and MYPYPATH to determine
                            module names of files passed (inverse: --no-
                            explicit-package-bases)
  --exclude PATTERN         Regular expression to match file names, directory
                            names or paths which mypy should ignore while
                            recursively discovering files to check, e.g.
                            --exclude '/setup\.py$'. May be specified more
                            than once, eg. --exclude a --exclude b
  -m MODULE, --module MODULE
                            Type-check module; can repeat for more modules
  -p PACKAGE, --package PACKAGE
                            Type-check package recursively; can be repeated
  -c PROGRAM_TEXT, --command PROGRAM_TEXT
                            Type-check program passed in as string
  files                     Type-check given files or directories

Environment variables:
  Define MYPYPATH for additional module search path entries.
  Define MYPY_CACHE_DIR to override configuration cache_dir path.

Installation on mega-linter Docker image

  • Dockerfile commands :
ENV MYPY_CACHE_DIR=/tmp
  • PIP packages (Python):