A plugin for flake8 integrating Mypy.

Overview

flake8-mypy

NOTE: THIS PROJECT IS DEAD

It was created in early 2017 when Mypy performance was often insufficient for in-editor linting. The Flake8 plugin traded correctness for performance, making Mypy only check a bare minimum of problems. These days Mypy is accelerated with mypyc, as well as uses aggressive caching to speed up incremental checks. It's no longer worth it to use hacks such as flake8-mypy.

What was the project anyway?

A plugin for Flake8 integrating mypy. The idea is to enable limited type checking as a linter inside editors and other tools that already support Flake8 warning syntax and config.

List of warnings

flake8-mypy reserves T4 for all current and future codes, T being the natural letter for typing-related errors. There are other plugins greedily reserving the entire letter T. To this I say: ¯\_(ツ)_/¯.

T400: any typing note.

T484: any typing error (after PEP 484, geddit?).

T498: internal mypy error.

T499: internal mypy traceback, stderr output, or an unmatched line.

I plan to support more fine-grained error codes for specific mypy errors in the future.

Two levels of type checking

mypy shines when given a full program to analyze. You can then use options like --follow-imports or --disallow-untyped-calls to exercise the full transitive closure of your modules, catching errors stemming from bad API usage or incompatible types. That being said, those checks take time, and require access to the entire codebase. For some tools, like an editor with an open file, or a code review tool, achieving this is not trivial. This is where a more limited approach inside a linter comes in.

Flake8 operates on unrelated files, it doesn't perform full program analysis. In other words, it doesn't follow imports. This is a curse and a blessing. We cannot find complex problems and the number of warnings we can safely show without risking false positives is lower. In return, we can provide useful warnings with great performance, usable for realtime editor integration.

As it turns out, in this mode of operation, mypy is still able to provide useful information on the annotations within and at least usage of stubbed standard library and third party libraries. However, for best effects, you will want to use separate configuration for mypy's standalone mode and for usage as a Flake8 plugin.

Configuration

Due to the reasoning above, by default flake8-mypy will operate with options equivalent to the following:

[mypy]
# Specify the target platform details in config, so your developers are
# free to run mypy on Windows, Linux, or macOS and get consistent
# results.
python_version=3.6
platform=linux

# flake8-mypy expects the two following for sensible formatting
show_column_numbers=True
show_error_context=False

# do not follow imports (except for ones found in typeshed)
follow_imports=skip

# since we're ignoring imports, writing .mypy_cache doesn't make any sense
cache_dir=/dev/null

# suppress errors about unsatisfied imports
ignore_missing_imports=True

# allow untyped calls as a consequence of the options above
disallow_untyped_calls=False

# allow returning Any as a consequence of the options above
warn_return_any=False

# treat Optional per PEP 484
strict_optional=True

# ensure all execution paths are returning
warn_no_return=True

# lint-style cleanliness for typing needs to be disabled; returns more errors
# than the full run.
warn_redundant_casts=False
warn_unused_ignores=False

# The following are off by default since they're too noisy.
# Flip them on if you feel adventurous.
disallow_untyped_defs=False
check_untyped_defs=False

If you disagree with the defaults above, you can specify your own mypy configuration by providing the --mypy-config= command-line option to Flake8 (with the .flake8/setup.cfg equivalent being called mypy_config). The value of that option should be a path to a mypy.ini or setup.cfg compatible file. For full configuration syntax, follow mypy documentation.

For the sake of simplicity and readability, the config you provide will fully replace the one listed above. Values left out will be using mypy's own defaults.

Remember that for the best user experience, your linter integration mode shouldn't generally display errors that a full run of mypy wouldn't. This would be confusing.

Note: chaing the follow_imports option might have surprising effects. If the file you're linting with Flake8 has other files around it, then in "silent" or "normal" mode those files will be used to follow imports. This includes imports from typeshed.

Tests

Just run:

python setup.py test

OMG, this is Python 3 only!

Yes, so is mypy. Relax, you can run Flake8 with all popular plugins as a tool perfectly fine under Python 3.5+ even if you want to analyze Python 2 code. This way you'll be able to parse all of the new syntax supported on Python 3 but also effectively all the Python 2 syntax at the same time.

By making the code exclusively Python 3.5+, I'm able to focus on the quality of the checks and re-use all the nice features of the new releases (check out pathlib) instead of wasting cycles on Unicode compatibility, etc.

License

MIT

Change Log

17.8.0

  • avoid raising errors in the default config which don't happen during a full run (disable warn_unused_ignores and warn_redundant_casts)

  • always run type checks from a temporary directory to avoid clashing with unrelated files in the same directory

17.3.3

  • suppress mypy messages about relative imports

17.3.2

  • bugfix: using Flake8 with absolute paths now correctly matches mypy messages

  • bugfix: don't crash on relative imports in the form from . import X

17.3.1

  • switch follow_imports from "silent" to "skip" to avoid name clashing files being used to follow imports within typeshed

  • set MYPYPATH by default to give stubs from typeshed higher priority than local sources

17.3.0

  • performance optimization: skip running mypy over files that contain no annotations or imports from typing

  • bugfix: when running over an entire directory, T484 is now correctly used instead of T499

17.2.0

  • first published version

  • date-versioned

Authors

Glued together by Łukasz Langa.

Comments
  • Compatibility with pythons that aren't 3.6

    Compatibility with pythons that aren't 3.6

    Not hard-coding the version of python this depends on

    When running flake8 as a pytest plugin it is not so straightforward to change command-line arguments to specify what version of python you are using, nor should you have to.

    opened by revmischa 2
  • issue with round

    issue with round

    got this error: T484 Argument 1 to "round" has incompatible type "Union[float, Decimal]"; expected "float"

    however that is in fact allowed:

    >>> round(Decimal(0.0))
    0
    
    opened by thehesiod 1
  •  Make temp file creation Windows compatible

    Make temp file creation Windows compatible

    On Windows the temp file must be closed, otherwise mypy can't open it again. Unfortunately, we then loose the nice to read with sugar and obviously must call os.remove manually.

    This is on top of #17 bc I had no way to test this otherwise.

    opened by kaste 0
  • Adapt test_clash for changes in mypy and typeshed master.

    Adapt test_clash for changes in mypy and typeshed master.

    UserDict is now concrete: https://github.com/python/typeshed/pull/1477

    And error message format changed slightly for non-subscripted generic types.

    Also added test docstring that would have saved me some time understanding what the test was about.

    opened by carljm 0
  • Error running flake8-mypy

    Error running flake8-mypy

    When I run flake8, I just get a bunch of these errors and nothing else from mypy:

    /home/ubuntu/.local/lib/python3.6/site-packages is in the MYPYPATH. Please remove it.
    See https://mypy.readthedocs.io/en/latest/running_mypy.html#how-mypy-handles-imports for more info
    
    opened by Dreamsorcerer 4
  • Improperly handling mypy summary from mypy 0.730 update

    Improperly handling mypy summary from mypy 0.730 update

    Mypy 0.730 introduced a change which adds a summary line when checking files which is on by default.

    This is picked up as an unmatched line and reported as a T499 error.

    Ideally the --no-error-summary flag would just be passed to mypy, but at the very least, no_error_summary=True needs to be added to the mypy_default.ini when the installed mypy version is >=0.730

    opened by cheeseandcereal 0
  • mypy.ini picked up implicitly and false defaults not overridden

    mypy.ini picked up implicitly and false defaults not overridden

    A mypy.ini in the current directory will be picked up implicitly, even if no config file is specified. This has a bad interaction with how the command line arguments are created, since false values are omitted, so those won't properly override the values in the implicitly picked up mypy.ini

    opened by msullivan 0
  • New release?

    New release?

    Any chance of a new release? The latest in PyPI is 17.8.0 and it struggles with Windows (https://github.com/ambv/flake8-mypy/pull/18).

    BTW there's no 17.8.0 tag in this repo.

    opened by jamesmyatt 2
  • Fails to Recognize

    Fails to Recognize "coding: utf-8-unix"

    Flake8-MyPy fails to recognize Python scripts that use the magic comment containing coding: utf-8-unix as a UTF8 file. This bug has persisted for several versions and I had been fixing it myself ( https://github.com/ambv/flake8-mypy/pull/12). Although, my fix no longer works in the newest version of flake8-mypy. The fix has already been applied to MyPy itself ( https://github.com/python/mypy/pull/5085 ), but this very helpful Flake8 plugin still lacks the fix.

    flake8 --version
    3.7.7 (flake8-mypy: 17.8.0, flake8-pyi: 19.3.0, mccabe: 0.6.1, pycodestyle: 2.5.0, pyflakes: 2.1.1, radon: 3.0.1, warn-symbols: 1.1.1) CPython 3.6.7 on Linux
    
    mypy --version
    mypy 0.701
    
    opened by DevynCJohnson 1
  • Cannot override writable attribute with a final one

    Cannot override writable attribute with a final one

    The below code should pass the check:

    class MongoDAOBase(abc.ABC):
        collection_name: str = NotImplemented
    
        @classmethod
        @abc.abstractmethod
        def create_index(cls) -> None:
            pass
    
    
    class PrivacySettingsDAO(MongoDAOBase):
        collection_name: Final = "privacy_settings" # complains
    
        @classmethod
        def create_index(cls) -> None:
            pass
    

    However, a T484 Cannot override writable attribute "collection_name" with a final oneis raised. This problem seems to be introduced recently. My local version (which is older) of flake8-mypy and mypy does not complain, but it fails in CI environment (which gets later version). I'm not sure if this is a flake8-mypy problem or mypy problem, so I just ask here first.

    opened by fr0der1c 0
Owner
Łukasz Langa
Python 3.8 & 3.9 Release Manager. llanga on Twitter. Python core developer, hobbyist musician, dad.
Łukasz Langa
❄️ A flake8 plugin to help you write better list/set/dict comprehensions.

flake8-comprehensions A flake8 plugin that helps you write better list/set/dict comprehensions. Requirements Python 3.6 to 3.9 supported. Installation

Adam Johnson 398 Dec 23, 2022
Flake8 plugin that checks import order against various Python Style Guides

flake8-import-order A flake8 and Pylama plugin that checks the ordering of your imports. It does not check anything else about the imports. Merely tha

Python Code Quality Authority 270 Nov 24, 2022
flake8 plugin that integrates isort

Flake8 meet isort Use isort to check if the imports on your python files are sorted the way you expect. Add an .isort.cfg to define how you want your

Gil Forcada Codinachs 139 Nov 8, 2022
Flake8 plugin to find commented out or dead code

flake8-eradicate flake8 plugin to find commented out (or so called "dead") code. This is quite important for the project in a long run. Based on eradi

wemake.services 277 Dec 27, 2022
flake8 plugin to run black for checking Python coding style

flake8-black Introduction This is an MIT licensed flake8 plugin for validating Python code style with the command line code formatting tool black. It

Peter Cock 146 Dec 15, 2022
A plugin for Flake8 that checks pandas code

pandas-vet pandas-vet is a plugin for flake8 that provides opinionated linting for pandas code. It began as a project during the PyCascades 2019 sprin

Jacob Deppen 146 Dec 28, 2022
flake8 plugin to catch useless `assert` statements

flake8-useless-assert flake8 plugin to catch useless assert statements Download or install on the PyPI page Violations Code Description Example ULA001

null 1 Feb 12, 2022
open source tools to generate mypy stubs from protobufs

mypy-protobuf: Generate mypy stub files from protobuf specs We just released a new major release mypy-protobuf 2. on 02/02/2021! It includes some back

Dropbox 527 Jan 3, 2023
Mypy stubs, i.e., type information, for numpy, pandas and matplotlib

Mypy type stubs for NumPy, pandas, and Matplotlib This is a PEP-561-compliant stub-only package which provides type information for matplotlib, numpy

Predictive Analytics Lab 194 Dec 19, 2022
The official GitHub mirror of https://gitlab.com/pycqa/flake8

Flake8 Flake8 is a wrapper around these tools: PyFlakes pycodestyle Ned Batchelder's McCabe script Flake8 runs all the tools by launching the single f

Python Code Quality Authority 2.6k Jan 3, 2023
Flake8 extension for checking quotes in python

Flake8 Extension to lint for quotes. Major update in 2.0.0 We automatically encourage avoiding escaping quotes as per PEP 8. To disable this, use --no

Zachary Heller 157 Dec 13, 2022
Flake8 wrapper to make it nice, legacy-friendly, configurable.

THE PROJECT IS ARCHIVED Forks: https://github.com/orsinium/forks It's a Flake8 wrapper to make it cool. Lint md, rst, ipynb, and more. Shareable and r

Life4 232 Dec 16, 2022
Automated security testing using bandit and flake8.

flake8-bandit Automated security testing built right into your workflow! You already use flake8 to lint all your code for errors, ensure docstrings ar

Tyler Wince 96 Jan 1, 2023
Flake8 extension for enforcing trailing commas in python

Flake8 Extension to enforce better comma placement. Usage If you are using flake8 it's as easy as: pip install flake8-commas Now you can avoid those a

Python Code Quality Authority 127 Sep 3, 2022
Tool to automatically fix some issues reported by flake8 (forked from autoflake).

autoflake8 Introduction autoflake8 removes unused imports and unused variables from Python code. It makes use of pyflakes to do this. autoflake8 also

francisco souza 27 Sep 8, 2022
Utilities for pycharm code formatting (flake8 and black)

Pycharm External Tools Extentions to Pycharm code formatting tools. Currently supported are flake8 and black on a selected code block. Usage Flake8 [P

Haim Daniel 13 Nov 3, 2022
Flake8 extension to provide force-check option

flake8-force Flake8 extension to provide force-check option. When this option is enabled, flake8 performs all checks even if the target file cannot be

Kenichi Maehashi 9 Oct 29, 2022
Pylint plugin for improving code analysis for when using Django

pylint-django About pylint-django is a Pylint plugin for improving code analysis when analysing code using Django. It is also used by the Prospector t

Python Code Quality Authority 544 Jan 6, 2023
A Pylint plugin to analyze Flask applications.

pylint-flask About pylint-flask is Pylint plugin for improving code analysis when editing code using Flask. Inspired by pylint-django. Problems pylint

Joe Schafer 62 Sep 18, 2022