Flake8 extension for enforcing trailing commas in python

Overview

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 annoying merge conflicts on dictionary and list diffs.

Errors

Different versions of python require commas in different places. Ignore the errors for languages you don't use in your flake8 config:

Code message
C812 missing trailing comma
C813 missing trailing comma in Python 3
C814 missing trailing comma in Python 2
C815 missing trailing comma in Python 3.5+
C816 missing trailing comma in Python 3.6+
C818 trailing comma on bare tuple prohibited
C819 trailing comma prohibited

Examples

lookup_table = {
    'key1': 'value',
    'key2': 'something'  # <-- missing a trailing comma
}

json_data = json.dumps({
    "key": "value",
}),                      # <-- incorrect trailing comma. json_data is now a tuple. Likely by accident.
Comments
  • Separate codes one element forms

    Separate codes one element forms

    This adds separate C82X codes for cases when a trailing comma is required in an enclosure with a single element. The reason is that sometimes people prefer not to have to add comas when for the enclosure is used mostly for grouping. For example:

    logger.info(
        'This is a long and excessively detailed '
        'possibly multi-line '
        'log message.'  # C822 missing trailing comma in one element enclosure
    )
    

    C822 can be exluded and calls with more than one arg get a separate C812 error code and can be left on:

    logger.info(
        'log message',
        extra={'extra': 'data'}  # C812 missing trailing comma in enclosure
    )
    

    This also adds separate codes for function definitions and single element collections.

    opened by iafilatov 21
  • Prohibit bare tuples

    Prohibit bare tuples

    We've had many production failures due to inadvertently having trailing commas on a line, resulting in a tuple where the single object was expected.

    I'd like a way to check for bare trailing commas. This PR reuses the existing C819 error for this case, but I'm open to creating a new error code for it.

    opened by catlee 15
  • Fix for multi-line list/dict comprehensions

    Fix for multi-line list/dict comprehensions

    I've added support for identifying multi-line list and dict comprehensions.

    This is implemented with a simple stack to track the current bracket context and whether that is for a list/dict comprehension (identified with the for token), which means that it still identifies missing trailing commas in non-comprehension structures that are within comprehensions.

    This fixes #3

    opened by danpalmer 7
  • Fix plugin for flake8 3.x

    Fix plugin for flake8 3.x

    This fixes the extension for flake8>=3, issue #20. I just followed the convention in the documentation: http://flake8.readthedocs.io/en/latest/plugin-development/registering-plugins.html

    Tried it with both flake8 2.6.2 & 3.0.4 - works in both.

    opened by heewa 5
  • setup.py should not require package

    setup.py should not require package

    When I prepared requirements file:

    # flake8
    flake8==2.5.4
    mccabe==0.4.0
    pep8==1.7.0
    pyflakes==1.0.0
    
    # flake8 extensions
    flake8-blind-except==0.1.0
    flake8-debugger==1.4.0
    flake8-pep257==1.0.5
    flake8-print==2.0.1
    flake8-quotes==0.1.2
    flake8-string-format==0.2.1
    flake8-commas==0.1.1
    flake8-import-order==0.6.1
    flake8-pep3101==0.2
    pep8-naming==0.3.3
    

    Then run pip install -r../requirements.dev.txt

    And got this:

    Collecting flake8-commas==0.1.1 (from -r ../requirements.txt (line 55))
      Using cached flake8-commas-0.1.1.tar.gz
        Complete output from command python setup.py egg_info:
        Traceback (most recent call last):
          File "<string>", line 1, in <module>
          File "/tmp/pip-build-VIomAr/flake8-commas/setup.py", line 3, in <module>
            import flake8_commas
          File "/tmp/pip-build-VIomAr/flake8-commas/flake8_commas.py", line 3, in <module>
            import pep8
        ImportError: No module named pep8
    

    I think it's better to update version in setup.py in similar way as in flake8_commas.py.

    Hope to see the new version (0.1.2) soon (: Thanks for extension!

    opened by srusskih 5
  • Is there a way to not require trailing commas on multi-line function calls?

    Is there a way to not require trailing commas on multi-line function calls?

    Is it possible to not require trailing commas on multiline function/method calls? At the moment they're getting flagged with C812, which we want for the other multiline errors, just not for function and method calls.

    Ideally if the error code for function and method calls was different than C812 we could make our own exceptions for those in our flake8 config.

    opened by dbarbar 4
  • print statement + string literal concatenation produces

    print statement + string literal concatenation produces

    I think flake8-commas is getting confused between python 3's print function and python 2's print statement followed by a concatenated string literal.

    This is valid python code:

    print (
        "abcdefghijklmnopqrstuvwxyz"
        "zyxwvutsrqponmlkjihgfedcba"
    )
    

    see: https://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation

    It is equivalent to:

    print "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba"
    

    However, Flake8-commas produces the warning:

    C813 missing trailing comma in Python 3
    

    Adding a trailing comma to the end of the concatenated string literal turns the statement into a tuple. Equivalent to this:

    print ("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba", )
    

    Which is not the same thing.

    Updated*

    opened by janrito 4
  • AttributeError: 'tuple' object has no attribute 'type'

    AttributeError: 'tuple' object has no attribute 'type'

    Traceback (most recent call last):
      File "venv/bin/flake8", line 11, in <module>
        sys.exit(main())
      File "/home/johny/work/result-api/venv/local/lib/python2.7/site-packages/flake8/main/cli.py", line 16, in main
        app.run(argv)
      File "/home/johny/work/result-api/venv/local/lib/python2.7/site-packages/flake8/main/application.py", line 322, in run
        self._run(argv)
      File "/home/johny/work/result-api/venv/local/lib/python2.7/site-packages/flake8/main/application.py", line 306, in _run
        self.run_checks()
      File "/home/johny/work/result-api/venv/local/lib/python2.7/site-packages/flake8/main/application.py", line 244, in run_checks
        self.file_checker_manager.run()
      File "/home/johny/work/result-api/venv/local/lib/python2.7/site-packages/flake8/checker.py", line 350, in run
        self.run_serial()
      File "/home/johny/work/result-api/venv/local/lib/python2.7/site-packages/flake8/checker.py", line 334, in run_serial
        checker.run_checks(self.results_queue, self.statistics_queue)
      File "/home/johny/work/result-api/venv/local/lib/python2.7/site-packages/flake8/checker.py", line 606, in run_checks
        self.run_ast_checks()
      File "/home/johny/work/result-api/venv/local/lib/python2.7/site-packages/flake8/checker.py", line 517, in run_ast_checks
        for (line_number, offset, text, check) in runner:
      File "/home/johny/work/result-api/venv/local/lib/python2.7/site-packages/flake8_commas/_base.py", line 262, in run
        for error in get_comma_errors(tokens):
      File "/home/johny/work/result-api/venv/local/lib/python2.7/site-packages/flake8_commas/_base.py", line 198, in get_comma_errors
        for token in tokens:
      File "/home/johny/work/result-api/venv/local/lib/python2.7/site-packages/flake8_commas/_base.py", line 122, in simple_tokens
        token = next(tokens)
      File "/home/johny/work/result-api/venv/local/lib/python2.7/site-packages/flake8_commas/_base.py", line 120, in <genexpr>
        tokens = (t for t in tokens if t.type != tokenize.COMMENT)
    
    opened by jankoprowski 4
  • initialised token

    initialised token

    tokens are not fed into the Token class when they are passed as file_tokens parameter in the CommaChecker class. Any check to the Token class properties will create an error. This PR fixes these errors.

    opened by janrito 4
  • Require commas after splat in Python 3

    Require commas after splat in Python 3

    In at least Python 3.5 and above it's valid to do:

    result = function(
        foo,
        bar,
        *args,
        more,
    )
    

    This also works for tuple & list literals (and possibly elsewhere).

    It would be great if flake8-commas could require a comma in such places when one is missing:

    result = function(
        foo,
        bar,
        *args
    )
    tpl = (
        foo,
        bar,
        *args
    )
    lst = [
        foo,
        bar,
        *args
    ]
    
    opened by PeterJCLaw 3
  • Wrong detection of C813

    Wrong detection of C813

    There is the following code:

    print(
        'too long line'
        ' second part'
        ' last part'
         )
    

    It uses https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation feature to split long lines. This code is correct based on regular flake8 checks.

    But it raises print.py:4:17: C813 missing trailing comma in Python 3 error.

    My expectation that it has to pass flake8-commas rules also, hasn't it?

    opened by extsoft 3
  • Missing trailing comma after multiplication reported as C815

    Missing trailing comma after multiplication reported as C815

    If a function argument contains multiplication, a C815 error ("... in Python 3.5+") is reported instead of C812, as if the expression includes tuple unpacking. This is misleading, because even Python 2.7 supports a trailing comma after multiplication.

    Example Code

    def foo(x): pass
    
    foo(
        1
    )
    foo(
        *(1,)
    )
    foo(
        2 * 1
    )
    

    Actual Behavior

    $ flake8 --select=C812,C815 repr.py
    repr.py:4:6: C812 missing trailing comma
    repr.py:7:10: C815 missing trailing comma in Python 3.5+
    repr.py:10:10: C815 missing trailing comma in Python 3.5+
    

    Expected Behavior

    I would expect the error reported for line 10 to be C812, not C815.

    Software Versions

    Python 3.9 flake8-commas 2.0.0

    opened by Cebtenzzre 0
  • Add test cases for python3.7 and python3.8

    Add test cases for python3.7 and python3.8

    Currently both tox.ini and travis.yml do not support latest python versions.

    I can send a PR with the fix!

    Related: https://github.com/wemake-services/wemake-python-styleguide/issues/1138

    opened by sobolevn 4
  • Ignore C812 when only one function argument

    Ignore C812 when only one function argument

    I'd like to ignore the error when there's only one argument to the function. For example:

    logger.debug(
        "Really long string "
        "implicitly joined"
    )
    
    opened by mlenzen 10
  • Ignore C812 when all items are on one line

    Ignore C812 when all items are on one line

    I'd like to ignore the enforcement of a trailing comma where all items are on a single line that isn't the same line as the opening bracket. For example,

    long_function_name(
        argument1, argument2, keyword=argument3
    )
    
    opened by mlenzen 6
Owner
Python Code Quality Authority
Organization for code quality tools (and plugins) for the Python programming language
Python Code Quality Authority
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
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
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
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
Optional static typing for Python 3 and 2 (PEP 484)

Mypy: Optional Static Typing for Python Got a question? Join us on Gitter! We don't have a mailing list; but we are always happy to answer questions o

Python 14.4k Jan 8, 2023
A Python Parser

parso - A Python Parser Parso is a Python parser that supports error recovery and round-trip parsing for different Python versions (in multiple Python

Dave Halter 520 Dec 26, 2022