Ошибка r503 flake8 как исправить

Anytime there is an inline assertion rule to be verified against a bool statement, using the python black formatter in VSCode will break the line causing flake8 to warn about rule W503 line break b...

1 Answer

Sorted by:

Reset to default

23

you have set ignore = in your configuration — you should use extend-ignore =

W504 and W503 conflict with each other (and are both disabled by default) — by setting ignore you’ve re-enabled them. extend-ignore does not have this problem as it augments the default set of ignored codes

note that when working with black you’ll want to use black’s recommended settings: https://github.com/psf/black/blob/06ccb88bf2bd35a4dc5d591bb296b5b299d07323/docs/guides/using_black_with_other_tools.md#flake8

max-line-length = 88
extend-ignore = E203

disclaimer: I’m the current flake8 maintainer

Improve this answer

answered Jun 29, 2021 at 3:08

anthony sottile's user avatar

anthony sottileanthony sottile

56.9k13 gold badges136 silver badges187 bronze badges

2

  • it also detects rule E501 and run the linter on the file doesn’t solve it

    – Antonio Santoro

    Jun 29, 2021 at 9:01

  • 1

    then add that to extend-ignore too (though the max-line-length is supposed to cover that)

    – anthony sottile

    Jun 30, 2021 at 11:48

Add a comment
 | 

Your Answer

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged

  • python
  • flake8
  • python-black

or ask your own question.

flake8-return

pypi
Python: 3.6+
Downloads
Build Status
Code coverage
License: MIT
Code style: black

Flake8 plugin that checks return values.
Flake8-return rule set is supported in ruff.

Installation

pip install flake8-return

Errors

  • R501 do not explicitly return None in function if it is the only possible return value.
def x(y):
    if not y:
        return
    return None  # error!
  • R502 do not implicitly return None in function able to return non-None value.
def x(y):
    if not y:
        return  # error!
    return 1
  • R503 missing explicit return at the end of function able to return non-None value.
def x(y):
    if not y:
        return 1
    # error!
  • R504 unnecessary variable assignment before return statement.
def x():
    a = 1
    # some code that not using `a`
    print('test')
    return a  # error!
  • R505 unnecessary else after return statement.
def x(y, z):
    if y:  # error!
        return 1
    else:
        return z
  • R506 unnecessary else after raise statement.
def x(y, z):
    if y:  # error!
        raise Exception(y)
    else:
        raise Exception(z)
  • R507 unnecessary else after continue statement.
def x(y, z):
    for i in y:
        if i < z:  # error!
            continue
        else:
            a = 0
  • R508 unnecessary else after break statement.
def x(y, z):
    for i in y:
        if i > z:  # error!
            break
        else:
            a = 0

Returns in asyncio coroutines also supported.

For developers

Show help

Create venv and install deps

Install git precommit hook

Run linters, autoformat, tests etc

Bump new version

make bump_major
make bump_minor
make bump_patch

Change Log

Unreleased

1.2.0 — 2022-10-28

  • Port no-else-break, no-else-continue, no-else-raise, no-else-return from pylint (#122) Calum Young
  • PEP 621: Migrate more config to pyproject.toml (#123) Christian Clauss
  • Fix/116/R504-try-except (#120) Calum Young
  • Update ci (#119) Calum Young
  • Fix/47/Update-R504-for-assignment-value (#117) Calum Young
  • Upgrade GitHub Actions (#113) Christian Clauss
  • Add a space to avoid a typo in R503 (#98) Christian Clauss
  • GitHub Action to lint Python code (#97) Christian Clauss
  • Typo fixes (#92) Aarni Koskela
  • Create codeql-analysis.yml Afonasev Evgeniy
  • Bump flake8-plugin-utils from 1.1.1 to 1.3.2 (#87) dependabot
  • Bump mypy from 0.812 to 0.971 (#114) dependabot
  • Bump pytest-cov from 3.0.0 to 4.0.0 (#124) dependabot
  • Bump pytest-cov from 2.11.1 to 3.0.0 (#102) dependabot
  • Bump pytest-mock from 3.6.0 to 3.6.1 (#91) dependabot
  • Bump pytest from 6.2.4 to 6.2.5 (#99) dependabot
  • Bump pylint from 2.8.2 to 2.10.2 (#100) dependabot
  • Bump pytest from 6.2.3 to 6.2.4 (#86) dependabot

1.1.3 — 2021-05-05

  • Error clarifications (#77) Clément Robert
  • fix linting (migrate to black 20.0b1) (#78) Clément Robert

1.1.2 — 2020-07-09

  • Make R504 visitors handle while loops (#56) Frank Tackitt
  • Rename allows-prereleases to allow-prereleases (#55) Frank Tackitt
  • Fix typo: → haven’t (#24) Jon Dufresne

1.1.1 — 2019-09-21

  • fixed #3 The R504 doesn’t detect that the variable is modified in loop
  • fixed #4 False positive with R503 inside async with clause

1.1.0 — 2019-05-23

  • update flask_plugin_utils version to 1.0

1.0.0 — 2019-05-13

  • skip assign after unpacking while unnecessary assign checking «(x, y = my_obj)»

0.3.2 — 2019-04-01

  • allow «assert False» as last function return

0.3.1 — 2019-03-11

  • add pypi deploy into travis config
  • add make bump_version command

0.3.0 — 2019-02-26

  • skip functions that consist only return None
  • fix false positive when last return inner with statement
  • add unnecessary assign error
  • add support tuple in assign or return expressions
  • add support asyncio coroutines

0.2.0 — 2019-02-21

  • fix explicit/implicit
  • add flake8-plugin-utils as dependency
  • allow raise as last function return
  • allow no return as last line in while block
  • fix if/elif/else cases

0.1.1 — 2019-02-10

  • fix error messages

0.1.0 — 2019-02-10

  • initial

flake8-return

pypi
Python: 3.6+
Downloads
Build Status
Code coverage
License: MIT
Code style: black

Flake8 plugin that checks return values.
Flake8-return rule set is supported in ruff.

Installation

pip install flake8-return

Errors

  • R501 do not explicitly return None in function if it is the only possible return value.
def x(y):
    if not y:
        return
    return None  # error!
  • R502 do not implicitly return None in function able to return non-None value.
def x(y):
    if not y:
        return  # error!
    return 1
  • R503 missing explicit return at the end of function able to return non-None value.
def x(y):
    if not y:
        return 1
    # error!
  • R504 unnecessary variable assignment before return statement.
def x():
    a = 1
    # some code that not using `a`
    print('test')
    return a  # error!
  • R505 unnecessary else after return statement.
def x(y, z):
    if y:  # error!
        return 1
    else:
        return z
  • R506 unnecessary else after raise statement.
def x(y, z):
    if y:  # error!
        raise Exception(y)
    else:
        raise Exception(z)
  • R507 unnecessary else after continue statement.
def x(y, z):
    for i in y:
        if i < z:  # error!
            continue
        else:
            a = 0
  • R508 unnecessary else after break statement.
def x(y, z):
    for i in y:
        if i > z:  # error!
            break
        else:
            a = 0

Returns in asyncio coroutines also supported.

For developers

Show help

Create venv and install deps

Install git precommit hook

Run linters, autoformat, tests etc

Bump new version

make bump_major
make bump_minor
make bump_patch

Change Log

Unreleased

1.2.0 — 2022-10-28

  • Port no-else-break, no-else-continue, no-else-raise, no-else-return from pylint (#122) Calum Young
  • PEP 621: Migrate more config to pyproject.toml (#123) Christian Clauss
  • Fix/116/R504-try-except (#120) Calum Young
  • Update ci (#119) Calum Young
  • Fix/47/Update-R504-for-assignment-value (#117) Calum Young
  • Upgrade GitHub Actions (#113) Christian Clauss
  • Add a space to avoid a typo in R503 (#98) Christian Clauss
  • GitHub Action to lint Python code (#97) Christian Clauss
  • Typo fixes (#92) Aarni Koskela
  • Create codeql-analysis.yml Afonasev Evgeniy
  • Bump flake8-plugin-utils from 1.1.1 to 1.3.2 (#87) dependabot
  • Bump mypy from 0.812 to 0.971 (#114) dependabot
  • Bump pytest-cov from 3.0.0 to 4.0.0 (#124) dependabot
  • Bump pytest-cov from 2.11.1 to 3.0.0 (#102) dependabot
  • Bump pytest-mock from 3.6.0 to 3.6.1 (#91) dependabot
  • Bump pytest from 6.2.4 to 6.2.5 (#99) dependabot
  • Bump pylint from 2.8.2 to 2.10.2 (#100) dependabot
  • Bump pytest from 6.2.3 to 6.2.4 (#86) dependabot

1.1.3 — 2021-05-05

  • Error clarifications (#77) Clément Robert
  • fix linting (migrate to black 20.0b1) (#78) Clément Robert

1.1.2 — 2020-07-09

  • Make R504 visitors handle while loops (#56) Frank Tackitt
  • Rename allows-prereleases to allow-prereleases (#55) Frank Tackitt
  • Fix typo: → haven’t (#24) Jon Dufresne

1.1.1 — 2019-09-21

  • fixed #3 The R504 doesn’t detect that the variable is modified in loop
  • fixed #4 False positive with R503 inside async with clause

1.1.0 — 2019-05-23

  • update flask_plugin_utils version to 1.0

1.0.0 — 2019-05-13

  • skip assign after unpacking while unnecessary assign checking «(x, y = my_obj)»

0.3.2 — 2019-04-01

  • allow «assert False» as last function return

0.3.1 — 2019-03-11

  • add pypi deploy into travis config
  • add make bump_version command

0.3.0 — 2019-02-26

  • skip functions that consist only return None
  • fix false positive when last return inner with statement
  • add unnecessary assign error
  • add support tuple in assign or return expressions
  • add support asyncio coroutines

0.2.0 — 2019-02-21

  • fix explicit/implicit
  • add flake8-plugin-utils as dependency
  • allow raise as last function return
  • allow no return as last line in while block
  • fix if/elif/else cases

0.1.1 — 2019-02-10

  • fix error messages

0.1.0 — 2019-02-10

  • initial

1 Answer

Sorted by:

Reset to default

23

you have set ignore = in your configuration — you should use extend-ignore =

W504 and W503 conflict with each other (and are both disabled by default) — by setting ignore you’ve re-enabled them. extend-ignore does not have this problem as it augments the default set of ignored codes

note that when working with black you’ll want to use black’s recommended settings: https://github.com/psf/black/blob/06ccb88bf2bd35a4dc5d591bb296b5b299d07323/docs/guides/using_black_with_other_tools.md#flake8

max-line-length = 88
extend-ignore = E203

disclaimer: I’m the current flake8 maintainer

Improve this answer

answered Jun 29, 2021 at 3:08

anthony sottile's user avatar

anthony sottileanthony sottile

56.9k13 gold badges136 silver badges187 bronze badges

2

  • it also detects rule E501 and run the linter on the file doesn’t solve it

    – Antonio Santoro

    Jun 29, 2021 at 9:01

  • 1

    then add that to extend-ignore too (though the max-line-length is supposed to cover that)

    – anthony sottile

    Jun 30, 2021 at 11:48

Add a comment
 | 

Your Answer

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged

  • python
  • flake8
  • python-black

or ask your own question.

Я продолжаю получать:

W503 line break before binary operator

Пожалуйста, помогите мне исправить мой код, так как я не могу понять, что здесь не так:

def check_actionable(self, user_name, op, changes_table):
        return any(user_name in row.inner_text() and row.query_selector(
            self.OPS[op]) is not
                   None and row.query_selector(self.DISABLED) is not None for
                   row in changes_table)

2 ответа

Лучший ответ

Правило W503 и правило W504 для flake8 противоречат друг другу. Я рекомендую вам добавить одного из них в список игнорирования вашего .flake8.

W503: разрыв строки перед бинарным оператором

W504: разрыв строки после бинарного оператора

ignore = D400,D300,D205,D200,D105,D100,D101,D103,D107,W503,E712

Приведенный ниже код претифицирован:

def check_actionable(self, user_name, op, changes_table):
    return any(user_name in row.inner_text() and
               row.query_selector(self.OPS[op]) is not None and
               row.query_selector(self.DISABLED) is not None for row in changes_table)

Некоторые пояснения по W503 и W504:

бинарный оператор: +, -, /, и, или, …

Чтобы передать W503, ваш код должен быть таким:

x = (1
     + 2)

Чтобы передать W504, ваш код должен быть таким:

x = (1 +
     2)


2

Will Zhao
1 Сен 2022 в 13:48

Другая (imo лучшая) альтернатива ignore (которая сбрасывает список игнорирования по умолчанию) заключается в использовании extend-ignore

По умолчанию как W503, так и W504 игнорируются (поскольку они конфликтуют и исторически переворачивались). есть и другие правила, которые также игнорируются по умолчанию, и которые вы можете сохранить.

extend-ignore = ABC123

ignore с другой стороны, сбрасывает список игнорирования, удаляя значения по умолчанию


Отказ от ответственности: я текущий сопровождающий flake8


0

Anthony Sottile
1 Сен 2022 в 15:36

Понравилась статья? Поделить с друзьями:
  • Ошибка require once
  • Ошибка r20 canon
  • Ошибка rockstar games launcher 1023
  • Ошибка request failed with status code 403
  • Ошибка r10 котел бакси