Flake8 extension for checking quotes in python

Overview

Flake8 Extension to lint for quotes.

Build Status

Major update in 2.0.0

We automatically encourage avoiding escaping quotes as per PEP 8. To disable this, use --no-avoid-escape (can be used in configuration file via avoid-escape).

Deprecation notice in 0.3.0

To anticipate multiline support, we are renaming --quotes to --inline-quotes. Please adjust your configurations appropriately.

Usage

If you are using flake8 it's as easy as:

pip install flake8-quotes

Now you don't need to worry about people like @sectioneight constantly complaining that you are using double-quotes and not single-quotes.

Warnings

This package adds flake8 warnings with the prefix Q0. You might want to enable this warning inside your flake8 configuration file. Typically that will be .flake8 inside the root folder of your project.

select = Q0

The current set of warnings is:

Code Description
Q000 Remove bad quotes
Q001 Remove bad quotes from multiline string
Q002 Remove bad quotes from docstring
Q003 Change outer quotes to avoid escaping inner quotes

Configuration

By default, we expect single quotes (') and look for unwanted double quotes ("). To expect double quotes (") and find unwanted single quotes ('), use the CLI option:

flake8 --inline-quotes '"'
# We also support "double" and "single"
# flake8 --inline-quotes 'double'
#
# We also support configuration for multiline quotes
# flake8 --inline-quotes '"' --multiline-quotes "'"
# We also support "'''"
# flake8 --inline-quotes '"' --multiline-quotes "'''"
#
# We also support docstring quotes similarly
# flake8 --inline-quotes '"' --docstring-quotes "'"
# flake8 --inline-quotes '"' --docstring-quotes "'''"

# We also support disabling escaping quotes
# flake8 --no-avoid-escape

or configuration option in tox.ini/setup.cfg.

[flake8]
inline-quotes = "
# We also support "double" and "single"
# inline-quotes = double
#
# We also support configuration for multiline quotes
# multiline-quotes = '
# We also support "'''"
# multiline-quotes = '''
#
# We also support docstring quotes similarly
# docstring-quotes = '
# docstring-quotes = '''
#
# We also support disabling escaping quotes
# avoid-escape = False

Caveats

We follow the PEP8 conventions to avoid backslashes in the string. So, no matter what configuration you are using (single or double quotes) these are always valid strings

s = 'double "quotes" wrapped in singles are ignored'
s = "single 'quotes' wrapped in doubles are ignored"
Comments
  • Incompatible with flake8 version 3

    Incompatible with flake8 version 3

    There is a beta version of flake8 version 3, which doesn't use config_options anymore so I get the following error:

    Traceback (most recent call last):
      File "/home/xzise/.pyenv/versions/3.5.1/bin/flake8", line 11, in <module>
        sys.exit(main())
      File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/main/cli.py", line 16, in main
        app.run(argv)
      File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/main/application.py", line 293, in run
        self._run(argv)
      File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/main/application.py", line 279, in _run
        self.initialize(argv)
      File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/main/application.py", line 270, in initialize
        self.register_plugin_options()
      File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/main/application.py", line 150, in register_plugin_options
        self.check_plugins.register_options(self.option_manager)
      File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/plugins/manager.py", line 451, in register_options
        list(self.manager.map(register_and_enable))
      File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/plugins/manager.py", line 261, in map
        yield func(self.plugins[name], *args, **kwargs)
      File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/plugins/manager.py", line 447, in register_and_enable
        call_register_options(plugin)
      File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/plugins/manager.py", line 357, in generated_function
        return method(optmanager, *args, **kwargs)
      File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/plugins/manager.py", line 207, in register_options
        add_options(optmanager)
      File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8_quotes/__init__.py", line 38, in add_options
        parser.config_options.extend(['quotes', 'inline-quotes'])
    

    More information:

    bug help wanted 
    opened by xZise 26
  • Repaired stdin support by moving from `pep8` to `flake8`

    Repaired stdin support by moving from `pep8` to `flake8`

    Instead of relying on pep8 importing itself, it can just use Flake8's pep8 import, which will either map to pep8 itself or to pycodestyle depending on what Flake8 is using. This changes the dependency from pep8 to flake8 and in theory pep8 could be uninstalled (if not used by Flake8). As this is actually a Flake8 plugin, I don't think it is a large issue, but maybe I'm missing something so I have highlighted it here.

    This is part of #37, so it will only work on Flake8 2.x. There is a bug report on Flake8 3.x, as that seems to not use pycodestyle's value and thus it'll return an empty string. But as 3.x is only beta, supporting that is not as urgent as supporting 2.x.

    And the remaining changes of #37 won't change anything in the handling of Flake8 2.x but just add support for 3.x, so the idea of this patch would still be required.

    opened by xZise 25
  • Add a rule to prevent unnessary \' in single-quoted strings

    Add a rule to prevent unnessary \' in single-quoted strings

    PEP-8 states:

    When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.

    Therefore 'isn\'t' should be rewritten as "isn't", but flake8-quotes currently does not recognize the first form as an error. I'd like to suggest adding it.

    enhancement help wanted 
    opened by 5j9 17
  • Support multiline quote check

    Support multiline quote check

    This also checks multiline quotes which can be configured separately. It also uses a different error code, so that repositories which don't want to use that new feature can just add the code to the ignored ones.

    This is another implementation fixing #25 similar to #26 (the additional tests from there could be transferred). The main reason for this pull request is that it removes the need for the dictionaries. It also does not complain when the string contains the wanted quote also in the multiline mode (not 100% sure how the other patch handles that), by using the same idea for both variants.

    There are a few things to mention:

    • The messages for Q000 and Q001 are very different because I don't think that the current message “Remove bad quotes” is very descriptive. But for backwards compatibility I left the current message.
    • ~~I'd prefer if #32 could be merged first. This is the reason for text = token.string.~~
    • ~~It changes code which would need to be overhauled when support for flake8 v3 is implemented (see #29 and #34). If possible this should be merged after it (especially as fixing #29 isn't that complex).~~
    opened by xZise 17
  • Add support for defining multiline quote type

    Add support for defining multiline quote type

    This fixes #25.

    • Improve naming and documentation of QUOTES and MULTILINE_QUOTES dictionaries inside QuoteChecker.
    • Add new --multiline-quotes option to allow customisation of multiline quote type.
    • Improve logic inside QuoteChecker.get_quotes_errors so that we can check single and multiline quotes separately.
    • Add new tests for mixed strings and fix tests broken by the new multiline rules.

    It seems there was a bug before that ignored multiline comments altogether which I have now fixed.

    opened by jackwilsdon 17
  • Support for the use case to enforce single-line strings, but not multiline strings

    Support for the use case to enforce single-line strings, but not multiline strings

    In our projects, we are trying to enforce always using ' for single line strings and flake8-quotes is perfect for that. However, for multiline strings, we use " for docstrings and ' for regular strings. Right now, they single-line strings and multiline strings emit the same warning, so we can't just ignore the latter. Also, --multiline-quotes allows configurability for that, but it's either ' or ", so in our project we can't use flake8-quotes at the moment. I think a good first step is to emit different errors for single-line and multiline. An optional next step is to have separate configurations for quotes for docstrings and regular multiline strings.

    enhancement help wanted 
    opened by karamanolev 16
  • Fetch package version at runtime w/setuptools

    Fetch package version at runtime w/setuptools

    The VERSION file contains the flake8_quotes version number. This file is included with the project when its repository is cloned by virtue of being under source control, and it is included in installable packages by virtue of being mentioned in MANIFEST.in. However, this file is never actually installed. Only files within the flake8_quotes namespace are available after installation.

    This is problematic because the flake8_quotes module includes a reference to this file. Installing flake8_quotes and then importing said module will trigger an import error, as the VERSION file is unavailable after installation. Fix this issue by doing the following to module flake8_quotes:

    1. Drop the reference to the VERSION file.
    2. Use setuptools to load the version number (from metadata.json).
    opened by Ichimonji10 14
  • Added variable docstring support

    Added variable docstring support

    logical lines that begin with a string and don't follow other docstrings are now considered to be docstrings fixes #100 requires flake8>=3.0 drop support for python 2.7 and 3.4 added some type assertions update tests for new docstring rules and to call flake8 directly

    opened by plinss 11
  • Relocated VERSION into flake8_quotes/__about__.py

    Relocated VERSION into flake8_quotes/__about__.py

    As reported in #21 and #23, we are having issues with externally installed flake8-quotes. We tried a few solutions to get a VERSION working but they weren't sticking.

    As a result, we went with the tested and true method used by flake8-import-order; using an __about__.py file.

    https://github.com/public/flake8-import-order/blob/2ac7052a4e02b4a8a0125a106d87465a3b9fd688/setup.py

    In this PR:

    • Relocated flake8_quotes and VERSION into flake8_quotes/__init__.py and flake8_quotes/__about__.py respectively
    • Updated release.sh
    • Updated setup.py to use __about__.py as in flake8-import-order
    • Removed unnecessary setuptools dependency from setup.py
    • Replaced py_modules with packages (seems to be what charlatan and flask use)

    Notes:

    We were able to reproduce the issue locally via the following:

    # Create temporary flake8-quotes install
    mkvirtualenv flake8-quotes
    git checkout master
    
    # Build `sdist` file as we do in `release.sh`
    python setup.py sdist
    
    # Navigate to parent directory to assure no issues
    cd ..
    
    # Install distribution file
    pip install flake8_quotes/dist/flake8-quotes-0.2.3.tar.gz
    
    # Verify error is reproduced
    flake8 flake8_quotes/
    
    # Try/rinse/repeat with different edits and recompiles
    

    /cc @zheller

    opened by twolfson 11
  • Cannot check source on stdin

    Cannot check source on stdin

    flake8-quotes fails with an exception when attempting to check source files provided on stdin.

    $ git clone [email protected]:zheller/flake8-quotes.git
    $ cd flake8-quotes
    $ mkvirtualenv flake8-quotes
    $ pip install flake8
    # This will work (before flake8-quotes is installed):
    $ cat flake8_quotes.py | flake8 -
    stdin:56:80: E501 line too long (93 > 79 characters)
    stdin:59:80: E501 line too long (100 > 79 characters)
    stdin:62:80: E501 line too long (84 > 79 characters)
    stdin:65:80: E501 line too long (100 > 79 characters)
    stdin:81:80: E501 line too long (86 > 79 characters)
    # But it will fail with flake8-quotes installed:
    $ pip install -e .
    (flake8-quotes)[mike@casey:flake8-quotes]$ cat flake8_quotes.py | flake8 -
    Traceback (most recent call last):
      File "/home/mike/envs/flake8-quotes/bin/flake8", line 11, in <module>
        sys.exit(main())
      File "/home/mike/envs/flake8-quotes/lib/python3.4/site-packages/flake8/main.py", line 33, in main
        report = flake8_style.check_files()
      File "/home/mike/envs/flake8-quotes/lib/python3.4/site-packages/flake8/engine.py", line 176, in check_files
        return self._retry_serial(self._styleguide.check_files, paths=paths)
      File "/home/mike/envs/flake8-quotes/lib/python3.4/site-packages/flake8/engine.py", line 167, in _retry_serial
        return func(*args, **kwargs)
      File "/home/mike/envs/flake8-quotes/lib/python3.4/site-packages/pep8.py", line 1672, in check_files
        runner(path)
      File "/home/mike/envs/flake8-quotes/lib/python3.4/site-packages/flake8/engine.py", line 121, in input_file
        return fchecker.check_all(expected=expected, line_offset=line_offset)
      File "/home/mike/envs/flake8-quotes/lib/python3.4/site-packages/pep8.py", line 1412, in check_all
        self.check_ast()
      File "/home/mike/envs/flake8-quotes/lib/python3.4/site-packages/pep8.py", line 1359, in check_ast
        for lineno, offset, text, check in checker.run():
      File "/home/mike/build/flake8-quotes/flake8_quotes.py", line 51, in run
        noqa_line_numbers = self.get_noqa_lines(file_contents)
      File "/home/mike/build/flake8-quotes/flake8_quotes.py", line 59, in get_noqa_lines
        tokens = [Token(t) for t in tokenize.generate_tokens(lambda L=iter(file_contents): next(L))]
    ValueError: I/O operation on closed file.
    
    opened by drmikehenry 11
  • Use flake8 provided tokens for analysis

    Use flake8 provided tokens for analysis

    The current flake8-quotes implementation don't use the infrastructure, provided by flake8 for plugins. The entry point QuoteChecker supports tree and filename arguments, but the first one (which is for AST tree, provided by flake8) - totally ignored! Then, QuoteChecker parses provided file by itself, which will lead to "invalid" issues like https://github.com/zheller/flake8-quotes/issues/92.

    I believe, this is a wrong situation and you could use instead the following skeleton to run checks per physical lines, provided by flake8:

    $ cat flake8_demo/setup.py 
    from setuptools import find_packages, setup
    
    setup(
      name='flake8-demo',
      packages=find_packages(),
      entry_points={
        'flake8.extension': [
          'X801 = flake8_demo.checker:demo_checker'],
      },
    )
    $ cat flake8_demo/flake8_demo/__init__.py 
    $ cat flake8_demo/flake8_demo/checker.py 
    import pprint
    
    
    def demo_checker(physical_line, tokens):
        pprint.pprint(physical_line)
    
    
    demo_checker.name = 'demo_checker'
    demo_checker.version = '0.0.1'
    

    This plugin correctly get input, provided by flake8/flake8-rst. For example:

    $ cat demo.rst
    Demo for flake8-rst and quotes
    
    >>> a = "spam"
    >>> f"no so short "
    ... f" formatted string with {a}"
    'not so short formatted string with spam'
    
    $ flake8-rst demo.rst 
    'a = "spam"\n'
    'f"no so short "\n'
    'f" formatted string with {a}"\n'
    demo.rst:3:5: D100 Missing docstring in public module
    demo.rst:5:5: I002 no configuration found (.isort.cfg or [isort] in configs)
    """
    enhancement help wanted 
    opened by skirpichev 10
  • Incorrect error message from `Q002` for docstrings

    Incorrect error message from `Q002` for docstrings

    If I put "Docstring" in a file, flake8-quotes complains (as it should), but with the error Q002 Single quote docstring found but double quotes preferred. This is incorrect, as they are double quotes, just not triple.

    opened by GideonBear 0
  • Replace setup.py with pyproject.toml

    Replace setup.py with pyproject.toml

    FYI: I see "DEPRECATION: flake8-quotes is being installed using the legacy 'setup.py install' method, because it does not have a 'pyproject.toml' and the 'wheel' package is not installed. pip 23.1 will enforce this behaviour change.", hence this PR.

    Second commit adds a simple GA workflow, see an example.

    Unfortunately, the pyproject.toml support will require setuptools>=61, that's why requires-python option was changed.

    opened by skirpichev 0
  • Support variable docstrings

    Support variable docstrings

    While not official, many documentation generators, e.g. Sphinx, pdoc, epydoc, PyCharm, etc., recognize docstrings after variables.

    flake8-quotes however classifies these as multi-line strings, so when using single quotes for multi-line strings and double quotes for docstrings, I get a bunch of false positives.

    Example:

    class Foo:
        """Class docsting."""
    
        def __init__(self):
            """Constructor docstring."""
            self.var = '''
                multiline string
            '''
            """var docstring."""
    
    enhancement help wanted 
    opened by plinss 7
  • No error after outer quotes are changed per Q003 if inner quotes are still escaped

    No error after outer quotes are changed per Q003 if inner quotes are still escaped

    Possibly related #69 , #77

    1. 'str\'i\'ng' Q003
    2. "str\'i\'ng" No errors

    The first line gives Q003 while the second line emits no errors. I took the ultimate aim of Q003 to be to eliminate escaped quotes wherever possible: if I am correct, then I suggest we should emit an additional error to actually do the un-escaping.

    I don't have a considered opinion about what that should look like, but if the pump needs priming it could be something like Q004 "Remove unnecessarily escaped quotes."

    enhancement help wanted 
    opened by rpdelaney 3
  • strings on multiple lines with different quotes

    strings on multiple lines with different quotes

    I'm really keen to use this on pydantic, however there's one ~~blocking~~ issue

    Take the following example:

            raise ConfigError(
                "validators should be used with fields and keyword arguments, not bare. "
                "E.g. usage should be `@validator('<field_name>', ...)`"
            )
    

    I would say both lines should use double quotes so they're the same even though only one line includes single quotes.

    I'm aware this would make analysis more complicated, but is it something you would consider? Either as default or via an option.

    enhancement help wanted 
    opened by samuelcolvin 5
Owner
Zachary Heller
the spice must flow
Zachary Heller
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
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
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
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
A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycodestyle.

flake8-bugbear A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycode

Python Code Quality Authority 869 Dec 30, 2022
❄️ 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 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 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
A plugin for flake8 integrating Mypy.

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 plu

Łukasz Langa 103 Jun 23, 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
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 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
Performant type-checking for python.

Pyre is a performant type checker for Python compliant with PEP 484. Pyre can analyze codebases with millions of lines of code incrementally – providi

Facebook 6.2k Jan 4, 2023
Unbearably fast O(1) runtime type-checking in pure Python.

Look for the bare necessities, the simple bare necessities. Forget about your worries and your strife. — The Jungle Book.

beartype 1.4k Jan 1, 2023
Pyright extension for coc.nvim

coc-pyright Pyright extension for coc.nvim Install :CocInstall coc-pyright Note: Pyright may not work as expected if can't detect project root correct

Heyward Fann 1.1k Jan 2, 2023
Simple Python style checker in one Python file

pycodestyle (formerly called pep8) - Python style guide checker pycodestyle is a tool to check your Python code against some of the style conventions

Python Code Quality Authority 4.7k Jan 1, 2023