R504 unnecessary variable assignment before return statement как исправить

Date you used flake8-return: 2020-06-18 flake8-return version used, if any: 1.1.1 Python version: 3.8.0 Operating System: Windows 10 Description flake8-return wrongly indicates R504 for the followi...

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

xqt opened this issue

Jun 18, 2020

· 6 comments


· Fixed by #117


Closed

flake8-return wrongly indicates R504

#47

xqt opened this issue

Jun 18, 2020

· 6 comments


· Fixed by #117

Assignees

@afonasev

Comments

@xqt

  • Date you used flake8-return: 2020-06-18
  • flake8-return version used, if any: 1.1.1
  • Python version: 3.8.0
  • Operating System: Windows 10

Description

flake8-return wrongly indicates R504 for the following samples:

    formatted = _USER_AGENT_FORMATTER.format(format_string, **values)
    # clean up after any blank components
    formatted = formatted.replace('()', '').replace('  ', ' ').strip()
    return formatted  # <<< wrongly indicated as R504 issue
def user_agent_username(username=None):

    if not username:
        return ''

    username = username.replace(' ', '_')  # Avoid spaces or %20.
    try:
        username.encode('ascii')  # just test, but not actually use it
    except UnicodeEncodeError:
        username = quote(username.encode('utf-8'))
    else:
        # % is legal in the default $wgLegalTitleChars
        # This is so that ops know the real pywikibot will not
        # allow a useragent in the username to allow through a hand-coded
        # percent-encoded value.
        if '%' in username:
            username = quote(username)
    return username  # <<< wrongly indicated as R504 issue

@afonasev

Thx for issue! I will try fix it.

@akx

Also seeing a false positive with a pattern like

    def resolve_from_url(self, url: str) -> dict:
        local_match = self.local_scope_re.match(url)
        if local_match:
            schema = get_schema(name=local_match.group(1))
            self.store[url] = schema
            return schema  # "R504 unecessary variable assignement before return statement."
        raise NotImplementedError(...)

where clearly schema is required as a local as it’s assigned into the dict.

@AIGeneratedUsername

One more example:

my_dict = {}

def my_func()
        foo = calculate_foo()
        my_dict["foo_result"] = foo
        return foo

Of course my code looks different. I showed a simplified example.

@ericbn

@xqt, your first example could be rewritten as:

    formatted = _USER_AGENT_FORMATTER.format(format_string, **values)
    # clean up after any blank components
    return formatted.replace('()', '').replace('  ', ' ').strip()

but I totally agree that from a style perspective the original code looks better.

Maybe R504 seems like a controversial rule.

@ericbn

Actually, maybe someone would want the opposite of R504 to keep a consistent style: «only return a variable (or a constant?), never an expression».

@peterjochum

Here is another simple example that triggers R504:

def get_bar_if_exists(obj):
    result = ""
    if hasattr(obj, "bar"):
        result = str(obj.bar)
    return result  # noqa: R504 - variable can be modified after declaration

Project description

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

Flake8 plugin that checks return values.

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

make help

Create venv and install deps

make init

Install git precommit hook

make precommit

Run linters, autoformat, tests etc

make pretty lint test

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

Download files

Download the file for your platform. If you’re not sure which to choose, learn more about installing packages.

Source Distribution

Built Distribution

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

Понравилась статья? Поделить с друзьями:
  • R20 starline ошибка
  • R2 online ошибка exception access violation
  • R07 nikon ошибка
  • R03 ошибка baxi
  • R01 старлайн ошибка