Skip to content

Instantly share code, notes, and snippets.

@Niccolum
Last active July 12, 2021 06:40
Show Gist options
  • Save Niccolum/7735082d3234817c0bf48bde51553cc9 to your computer and use it in GitHub Desktop.
Save Niccolum/7735082d3234817c0bf48bde51553cc9 to your computer and use it in GitHub Desktop.

Flake8

pep8 warning

E***

  • E1** Indentation
  • E2** Whitespace
  • E3** Blank line
  • E4** Import
  • E5** Line length
    • E501 Line too long
  • ✔️ E502 the backslash is redundant between brackets
  • E7** Statement
    • E701 multiple statements on one line (colon)
    • E702 multiple statements on one line (semicolon)
    • E703 statement ends with a semicolon
  • ✔️ E704 multiple statements on one line (def)
  • ✔️ E711 comparison to None should be ‘if cond is None:’
  • ✔️ E712 comparison to True should be ‘if cond is True:’ or ‘if cond:’
  • ✔️ E713 test for membership should be ‘not in’
  • ✔️ E714 test for object identity should be ‘is not’
  • ✔️ E721 do not compare types, use ‘isinstance()’
  • ✔️ E722 do not use bare except, specify exception instead
  • ✔️ E731 do not assign a lambda expression, use a def
  • ✔️ E741 do not use variables named ‘l’, ‘O’, or ‘I’
  • ✔️ E742 do not define classes named ‘l’, ‘O’, or ‘I’
  • ✔️ E743 do not define functions named ‘l’, ‘O’, or ‘I’

✔️ E9** Runtime

  • ✔️ E901 SyntaxError or IndentationError
  • ✔️ E902 IOError

W***

  • W1** Indentation warning
  • W2** Whitespace warning
  • W3** Blank line warning
  • W5** Line break warning
  • W6** Deprecation warning
  • ✔️ W605 invalid escape sequence ‘x’
  • ✔️ W606 ‘async’ and ‘await’ are reserved keywords starting with Python 3.7

PyFlakes codes

  • ✔️ F401 module imported but unused

  • ✔️ F402 import module from line N shadowed by loop variable

  • ✔️ F403 ‘from module import *’ used; unable to detect undefined names

  • ✔️ F404 future import(s) name after other statements

  • ✔️ F405 name may be undefined, or defined from star imports: module

  • ✔️ F406 ‘from module import *’ only allowed at module level

  • ✔️ F407 an undefined future feature name was imported

  • ✔️ F501 invalid % format literal

  • ✔️ F502 % format expected mapping but got sequence

  • ✔️ F503 % format expected sequence but got mapping

  • F504 % format unused named arguments

  • ✔️ F505 % format missing named arguments

  • ✔️ F506 % format mixed positional and named arguments

  • ✔️ F507 % format mismatch of placeholder and argument count

  • ✔️ F508 % format with * specifier requires a sequence

  • ✔️ F509 % format with unsupported format character

  • ✔️ F521 .format(...) invalid format string

  • F522 .format(...) unused named arguments

  • ✔️ F523 .format(...) unused positional arguments

  • ✔️ F524 .format(...) missing argument

  • ✔️ F525 .format(...) mixing automatic and manual numbering

  • ✔️ F541 f-string without any placeholders

  • ✔️ F601 dictionary key name repeated with different values (difference in https://github.com/PyCQA/pyflakes/blob/master/pyflakes/test/test_dict.py)

  • ✔️ F602 dictionary key variable name repeated with different values (difference in https://github.com/PyCQA/pyflakes/blob/master/pyflakes/test/test_dict.py)

  • ✔️ F621 too many expressions in an assignment with star-unpacking

  • ✔️ F622 two or more starred expressions in an assignment (a, *b, *c = d)

  • ✔️ F631 assertion test is a tuple, which is always True

  • ✔️ F632 use ==/!= to compare str, bytes, and int literals

  • ✔️ F633 use of >> is invalid with print function

  • ✔️ F634 if test is a tuple, which is always True

  • ✔️ F701 a break statement outside of a while or for loop

  • ✔️ F702 a continue statement outside of a while or for loop

  • ✔️ F703 a continue statement in a finally block in a loop

  • ✔️ F704 a yield or yield from statement outside of a function

  • ✔️ F705 a return statement with arguments inside a generator

  • ✔️ F706 a return statement outside of a function/method

  • ✔️ F707 an except: block as not the last exception handler

  • F721 syntax error in doctest

  • ✔️ F722 syntax error in forward annotation

  • ✔️ F723 syntax error in type comment

  • ✔️ F811 redefinition of unused name from line N

  • ✔️ F821 undefined name name

  • ✔️ F822 undefined name name in all

  • ✔️ F823 local variable name … referenced before assignment

  • ✔️ F831 duplicate argument name in function definition

  • ✔️ F841 local variable name is assigned to but never used

  • ✔️ F901 raise NotImplemented should be raise NotImplementedError

McCabe complexity

C9**

  • ✔️ C901 %r is too complex (%d)

pep8-naming

N8**

  • ✔️ N801 class names should use CapWords convention (class names)
  • ✔️ N802 function name should be lowercase (function names)
  • ✔️ N803 argument name should be lowercase (function arguments)
  • ✔️ N804 first argument of a classmethod should be named 'cls' (function arguments)
  • ✔️ N805 first argument of a method should be named 'self' (function arguments)
  • ✔️ N806 variable in function should be lowercase
  • ✔️ N807 function name should not start and end with '__'
  • ✔️ N811 constant imported as non constant (constants)
  • ✔️ N812 lowercase imported as non-lowercase
  • ✔️ N813 camelcase imported as lowercase
  • ✔️ N814 camelcase imported as constant (distinct from N817 for selective enforcement)
  • ✔️ N815 mixedCase variable in class scope (constants, method names)
  • ✔️ N816 mixedCase variable in global scope (constants)
  • ✔️ N817 camelcase imported as acronym (distinct from N814 for selective enforcement)
  • ✔️ N818 error suffix in exception names (exceptions)

Plugins

flake8-blind-except

  • B901 blind except: statement (copy of E722)
  • ✔️ B902 blind except Exception: statement

flake8-bandit (Remove it. We use raw bandit instead)

flake8-bugbear

  • B0**

    • B001 Do not use bare except (copy of E722)
    • B002 Writing ++n. You meant n += 1
    • B003 Assigning to os.environ doesn't clear the environment. Subprocesses are going to see outdated variables, in disagreement with the current process. Use os.environ.clear() or the env= argument to Popen.
    • B004 Using hasattr(x, '__call__') to test if x is callable. Use callable(x) instead.
    • B005 Using .strip() with multi-character strings is misleading the reader. It looks like stripping a substring. Move your character set to a constant if this is deliberate. Use .replace() or regular expressions to remove string fragments.
  • ✔️ B006 Do not use mutable data structures for argument defaults.

  • ✔️ B007 Loop control variable not used within the loop body. If this is intended, start the name with an underscore.

    • B008 Do not perform function calls in argument defaults. The call is performed only once at function definition time. All calls to your function will reuse the result of that definition-time function call. If this is intended, assign the function call to a module-level variable and use that variable as a default value.
    • B009 Do not call getattr(x, 'attr'), instead use normal property access: x.attr. Missing a default to getattr will cause an AttributeError to be raised for non-existent properties. There is no additional safety in using getattr if you know the attribute name ahead of time.
    • B010 Do not call setattr(x, 'attr', val), instead use normal property access: x.attr = val. There is no additional safety in using setattr if you know the attribute name ahead of time.
    • B011 Do not call assert False since python -O removes these calls. Instead callers should raise AssertionError().
  • ✔️ B012 Use of break, continue or return inside finally blocks will silence exceptions or override return values from the try or except blocks. To silence an exception, do it explicitly in the except block. To properly use a break, continue or return refactor your code so these statements are not in the finally block.

  • ✔️ B013 A length-one tuple literal is redundant. Write except SomeError: instead of except (SomeError,):.

  • ✔️ B014 Redundant exception types in except (Exception, TypeError):. Write except Exception:, which catches exactly the same exceptions.

  • ✔️ B015 Pointless comparison. This comparison does nothing but waste CPU instructions. Either prepend assert or remove it.

    • B016 Cannot raise a literal. Did you intend to return it or raise an Exception?
    • B017 self.assertRaises(Exception): should be considered evil. It can lead to your test passing even if the code being tested is never executed due to a typo. Either assert for a more specific exception (builtin or custom), use assertRaisesRegex, or use the context manager form of assertRaises (with self.assertRaises(Exception) as ex:) with an assertion against the data available in ex.
  • B3** Python 3 compatibility warnings

flake8-builtins

  • ✔️ A001 variable "max" is shadowing a python builtin
  • ✔️ A002 argument "dict" is shadowing a python builtin

flake8-cognitive-complexity (delete it. Analog metric as mccabe cyclimatic complexity)

  • CCR001 Cognitive complexity is too high (X > Y)

flake8-commas (delete it. It must be part of formatter)

  • C8**

flake8-comprehensions

  • C4**
  • ✔️ C400-402: Unnecessary generator - rewrite as a <list/set/dict> comprehension.
  • ✔️ C403-404: Unnecessary list comprehension - rewrite as a <set/dict> comprehension.
  • ✔️ C405-406: Unnecessary <list/tuple> literal - rewrite as a <set/dict> literal.
    • C408: Unnecessary <dict/list/tuple> call - rewrite as a literal.
  • ✔️ C409-410: Unnecessary <list/tuple> passed to <list/tuple>()
  • ✔️ C411: Unnecessary list call - remove the outer call to list().
  • ✔️ C413: Unnecessary <list/reversed> call around sorted().
  • ✔️ C414: Unnecessary <list/reversed/set/sorted/tuple> call within <list/set/sorted/tuple>().
  • ✔️ C415: Unnecessary subscript reversal of iterable within <reversed/set/sorted>().
  • ✔️ C416: Unnecessary <list/set> comprehension - rewrite using <list/set>().

flake8-docstrings (Choose docs conventions and use it. Will we use it?)

flake8-eradicate (Delete it. Use eradicate formatter instead)

flake8-mutable (Delete it. Use flake8-bugbear instead)

  • M511 mutable default arg of type {}' (duplicate of B006)

flake8-mypy (maybe use raw mypy instead? We have problems with that plugin on windows)

flake8-polyfill (remove it. It helper for another plugins)

flake8-print

  • ✔️ T001 print found
  • ✔️ T002 Python 2.x reserved word print used
  • ✔️ T003 pprint found
  • ✔️ T004 pprint declared
@amartiushkov-ms
Copy link

Не понял как поставить галочку, но лично плюсанул бы
E2** Whitespace
E3** Blank line
Это даже пайчарм всегда подсвечивает, что раздражает.

@Niccolum
Copy link
Author

Niccolum commented Jul 8, 2021

Просто кликаешь на чекбокс слева и всё.
Конкретно тут не выделял то, что должен в автоматическом режиме обрабатывать форматтер. В частности - E2** и E3**. Оставил только то, что должно выбрасывать предупреждение, чтобы мы это исправляли руками.

@krikunts
Copy link

krikunts commented Jul 9, 2021

Непонятно по какой логике выключены некоторые галки, в частности F504, F523, C408

@Niccolum
Copy link
Author

Niccolum commented Jul 9, 2021

Это, как я ранее писал, мои личные предпочтения. Можем включить, если будут спорные, или выключить те, которые не нравятся.
В частности

F504 - иногда бывает такая ситуация, когда у нас большой словарик с разными данными, а для форматирования нужно лишь пару значений оттуда. F504 ругнётся в этом случае. Я просто наталкивался пару раз на такой кейс. Но если думаешь, что лучше в таком случае пусть ругается - я не против.
F523 - да, он нужен. Перепутал с F522 (аналогия с F504). Поправил.
C408 - мне кажется чисто субъективная штука. Всегда пиши как {"foo": "bar"} вместо dict(foo="bar")

@krikunts
Copy link

krikunts commented Jul 9, 2021

Если реально есть такие кейсы, то F504 и F522 ок, можно выключить.
С408 я бы включила, учитывая включенные остальные C4**, иначе неконсистентно выходит

@Niccolum
Copy link
Author

Niccolum commented Jul 9, 2021

Ок, принято

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment