flake8-return 1.2.0

pip install flake8-return Copy PIP instructions

Released: Oct 28, 2022

Flake8 plugin that checks return values

Verified details

Maintainers.

Avatar for afonasev from gravatar.com

Unverified details

Project links, github statistics.

  • Open issues:

View statistics for this project via Libraries.io , or by using our public dataset on Google BigQuery

License: MIT License (MIT)

Author: Afonasev Evgeniy

Tags flake8, plugin, return

Requires: Python >=3.6, <4.0

Classifiers

  • OSI Approved :: MIT License
  • Python :: 3
  • Python :: 3.6
  • Python :: 3.7
  • Python :: 3.8
  • Python :: 3.9
  • Python :: 3.10

Project description

Flake8-return.

unnecessary variable assignment before return statement

Flake8 plugin that checks return values.

Installation

  • R501 do not explicitly return None in function if it is the only possible return value.
  • R502 do not implicitly return None in function able to return non-None value.
  • R503 missing explicit return at the end of function able to return non-None value.
  • R504 unnecessary variable assignment before return statement.
  • R505 unnecessary else after return statement.
  • R506 unnecessary else after raise statement.
  • R507 unnecessary else after continue statement.
  • R508 unnecessary else after break statement.

Returns in asyncio coroutines also supported.

For developers

Create venv and install deps, install git precommit hook, run linters, autoformat, tests etc, bump new version, 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

Project details, release history release notifications | rss feed.

Oct 28, 2022

May 5, 2021

Jul 9, 2020

Sep 20, 2019

May 23, 2019

May 13, 2019

Apr 1, 2019

Mar 11, 2019

Feb 26, 2019

Feb 21, 2019

Feb 9, 2019

Download files

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

Source Distribution

Uploaded Oct 28, 2022 Source

Built Distribution

Uploaded Oct 28, 2022 Python 3

Hashes for flake8-return-1.2.0.tar.gz

Hashes for flake8_return-1.2.0-py3-none-any.whl.

  • português (Brasil)

Supported by

unnecessary variable assignment before return statement

no-useless-return

Disallow redundant return statements

Some problems reported by this rule are automatically fixable by the --fix command line option

A return; statement with nothing after it is redundant, and has no effect on the runtime behavior of a function. This can be confusing, so it’s better to disallow these redundant statements.

Rule Details

This rule aims to report redundant return statements.

Examples of incorrect code for this rule:

Examples of correct code for this rule:

When Not To Use It

If you don’t care about disallowing redundant return statements, you can turn off this rule.

This rule was introduced in ESLint v3.9.0.

  • Rule source
  • Tests source
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL query help documentation »
  • CodeQL query help for JavaScript and TypeScript »

Return statement assigns local variable ¶

Click to see the query in the CodeQL repository

Assigning a local variable in a return statement is useless, since the local variable will go out of scope immediately and its new value is lost.

Recommendation ¶

Closely examine the code in question to understand the original intention. For instance, the assignment may originally have referred to a variable from another scope that accidentally was shadowed due to a renaming; in this case, perform another renaming to make it visible again. Or maybe the assignment was meant to assign to a property of the receiver object and the programmer inadvertently forgot to qualify it by this ; address this by providing the required qualification. Finally, the assignment may simply be unnecessary, in which case it can be removed.

In the following example, the getName method of Person contains a useless assignment to name .

The assignment serves no obvious purpose and should be removed:

References ¶

Wikipedia: Dead store .

Common Weakness Enumeration: CWE-563 .

flake8-return

afonasev / flake8-return Goto Github PK

Flake8 plugin for return expressions checking.

License: MIT License

flake8-return's Introduction

Flake8-return.

pypi

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

Installation

  • R501 do not explicitly return None in function if it is the only possible return value.
  • R502 do not implicitly return None in function able to return non-None value.
  • R503 missing explicit return at the end of function able to return non-None value.
  • R504 unnecessary variable assignment before return statement.
  • R505 unnecessary else after return statement.
  • R506 unnecessary else after raise statement.
  • R507 unnecessary else after continue statement.
  • R508 unnecessary else after break statement.

Returns in asyncio coroutines also supported.

For developers

Create venv and install deps, install git precommit hook, run linters, autoformat, tests etc, bump new version, 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

Flake8-return's people, contributors.

afonasev avatar

flake8-return's Issues

Flake8-return does not recognize `assert false` as an implicit return..

  • Date you used flake8-return: today
  • flake8-return version used, if any: 0.3.1
  • Python version, if any: Python 3.7.2
  • Operating System: Linux

Description

We sometimes end a method with assert False, "some reason" as a sanity check. The current version of flake8-return sees this as a violation of R503.

This assert False is equivalent to raise AssertionError which flake8-return does recognize. We would like to see flake8-return treat both statements as equivalent.

In some circumstances the error R506 can be dangerous if the `raise` will be changed later

  • Date you used flake8-return: 28.10.2022
  • flake8-return version used, if any: 1.2.0
  • Python version, if any: 3.10.8
  • Operating System: MacOS/Linux

The error reported for R506 can be dangerous in fast changing development environment

Let assume we have this piece of code

The error reported is the following:

Now let assume we change it according to the proposal, but after short period of time another developer come and changed the code slightly (because IF can be quite big and not intuitive), he removed raise and add the handling of situation inside and removed try...except all together. Now let's see the result:

As we can see the result is not what the developer expected, but... sometimes it is very difficult to notice such issues. As elif has SOME MEANING behind, usually...

Plugin crashes when used with stdin

  • Date you used flake8-return: 27-11-2020
  • flake8-return version used, if any: 1.1.2
  • Python version, if any: Python 3.86
  • Operating System: Ubuntu 20.4

When emacs' lsp-mode calls flake 8 on a file (in order to lint it), the command errors out. I strongly suspect the issue is the same as the one reported here: sco1/flake8-annotations#52 My reason for suspecting the error lies within this plugin is the fact that the error goes away when I remove this plugin.

Opened the file, activated the virtual env, and started the language server (which called flake8)

What I expected

Flake8 gives results and the pyls lints my code

Stack trace below

False positive on R504

  • Date you used flake8-return: 2019-05-16
  • flake8-return version used, if any: 1.0.0
  • Python version, if any: 3.7.1
  • Operating System: Debian

The R504 doesn't detect that the variable is conditionally modified prior to return.

Initial Update

The bot created this issue to inform you that pyup.io has been set up on this repo. Once you have closed it, the bot will open pull requests for updates as soon as they are available.

R503 false positive

  • Date you used flake8-return: 5/18/2023
  • Python version, if any: 3.8
  • Operating System: macOS

For this type of function:

flake8-returns gives R503 violation. I think this may be a false positive

Create v1.1.3 tag

  • Date you used flake8-return: 28/10/2022
  • flake8-return version used, if any: Hoping to use v1.1.3
  • Operating System: WSL

I was updating our pre-commit hooks to use flake8-return (rather than a forked version), but as the v1.1.3 tag has not been created on Github, the pre-commit hook does not make use of the changes introduced in v1.1.3 on PyPI.

@afonasev , please could you create a tag for v1.1.3 so that pre-commit makes use of the recent updates?

The abridged pre-commit config used below throws a false positive for R504, which has been fixed in the version released on PyPI.

flake8-return wrongly indicates R504

  • 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

flake8-return wrongly indicates R504 for the following samples:

Variable assignment inside try/except blocks is not handled properly

  • Date you used flake8-return: 09-09-2022
  • flake8-return version used, if any: 1.1.3
  • Python version, if any: 3.10.6
  • Operating System: macOS Monterey 12.5.1

Describe what you were trying to get done. Tell us what happened, what went wrong, and what you expected to happen.

Consider the following functions

The variable success is changed (or may be changed) inside try/except blocks. However, running flake8 generates the following error: R504 unecessary variable assignement before return statement.

Should allow raise at end of function, in addition to assert

flake8-return version 1.1.3 allows this construct

but disallows this one

I think they should be treated the same?

R505+R508 false positive

  • Date you used flake8-return: 2024-01-24
  • Python version, if any: 3.7
  • Operating System: Linux (Ubuntu)

R505 & R508 produce false-positives when an earlier branch does not return / break .

Same thing if the if -chain is contained in a loop and the return is a break instead.

Note that not using an elif after causes a behavior change: print("2") will be called when it shouldn't be. These warnings should only trigger if every case in the if / elif / else chain return s, break s, or raise s.

Incorrect error reporting R507 for `elif` + `continue` if after the `continue` statement `elif` is following

Invalid error reported for R507 because of some complex context

We have some if...elif... clause like this:

For this case we are getting this error:

If we follow the suggestion and fix the issue, then we have different output:

Can we do something to this? I have tried to apply the suggested errors on our codebase and this issue appeared.

port no-else-break, no-else-continue, no-else-raise, no-else-return from pylint

This fixes the extremely annoying construct:

this is a feature request

Support match/case operator

  • Date you used flake8-return: 26-08-22
  • Python version, if any: 3.10.2
  • Operating System: MacOS 12.5.1

match/case construction not supported

Feature request: taking type hints into account ?

  • Date you used flake8-return: feb 6 2021
  • Python version, if any: 3.8.5

I have a decorator that's specifically designed to return either None or a function depending on the CPU rank so that only the root one exectutes the decoreated function. Here's the gist of it

I'm getting a R502 error of course, so I tried adding type hints to avoid using noqas

but the error persists, though I'd argue it shouldn't (in an ideal world). I know that this is a sizeable feature to ask but is there any chance you'd consider taking type hints into account ? In any case thanks for the tool, it's worth using for 504 alone !

False positive with R503 inside with clause

  • Date you used flake8-return: 8/16/2019
  • flake8-return version used, if any: 1.1.0
  • Python version, if any: 3.6.6
  • Operating System: OSX

With a function like the following:

This is valid because there can be no other return than the one inside the with context. If enter/exit raise then nothing after it will run. The one way this is not true is if you capture the exeption with a try/except around the async with clause.

R503: from function with returns in match/case.

  • Date you used flake8-return: 2023/02/02
  • Python version, if any: 3.11.1
  • Operating System: ubuntu linux

Running through pre-commit with flake8-return listed as an additional dependency for the flake8 repo.

This function:

raises R503 missing explicit return at the end of function able to return non-None value.

Incorrectly marks variables updated in a while loop

  • Date you used flake8-return: Jul 6, 2020
  • Python version, if any: Python 3.8.3
  • Operating System: Arch Linux on Linux 5.7.4

flake8-return seemingly fails to detect changes to a variable modified in a while loop.

A R504 error is detected at each return there, in doit() , Node.__str__ , and Node.tail

R506 false positive when raise is used in elif

  • Date you used flake8-return: 15th December 2022
  • Python version, if any: 3.9.2

Linting following code:

The else is necessary as there is additional if before which has side effects and removing else would overwrite that. The code is simplified from real-world code.

Invalid error reported for R505 simple if - elif pattern

  • Date you used flake8-return: 2022-10-31
  • Python version, if any: Python 3.10.6

I think this pattern should be passed.

Possible False Positive for R504

  • Date you used flake8-return: Oct 25th 2022
  • Python version, if any: 3.10.7

I have a fixture that creates a mock object, patches a library to return that mock object for a specific method and then returns the mock object so that assertions can be made on it. It seems quite clear that I am in fact using the variable, not sure why it's triggering the linting rule.

I was able to refactor the code to make the lint pass (the second example below), but that code is much less intuitive to me and messy.

Bad `R504` for assignment in a loop body

Running flake8-return with Python 3.7, I get an R504 error for the following code:

While any_failed is not used in any other expressions before being returned, it's still important to run all cleanup tasks instead of returning immediately after the first error. Perhaps R504 should be disabled when the assignment is in a loop and the return statement is not?

R504 false positive when variable is a function parameter

  • Date you used flake8-return: 2023-03-16
  • Python version, if any: 3.10.9

variables that are function parameters should not be treated as unnecessary, cursory skim of https://github.com/afonasev/flake8-return/blob/master/flake8_return/mixins/unnecessary_assign.py looks like it doesn't look at FunctionDef or AsyncFunctionDef at all which explains it.

False-Positive R504 in non-trivial if-else Block

  • Date you used flake8-return: 2023-02-11
  • Python version, if any: 3.10
  • Operating System: Windows 11

The application of R504 unnecessary variable assignment before return statement seems wrong here. I've specifically not inlined my return statement in order to have a single return in this "complicated" if-else block.

The example on the homepage was for the trivial case of an unnecessary assignment, but for something more complicated like this I think it should not flag R504 anywhere in the method.

Recommend Projects

A declarative, efficient, and flexible JavaScript library for building user interfaces.

🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

An Open Source Machine Learning Framework for Everyone

The Web framework for perfectionists with deadlines.

A PHP framework for web artisans

Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

Some thing interesting about web. New door for the world.

A server is a program made to process requests and deliver data to clients.

Machine learning

Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

Visualization

Some thing interesting about visualization, use data art

Some thing interesting about game, make everyone happy.

Recommend Org

We are working to build community through open source technology. NB: members must have two-factor auth.

Open source projects and samples from Microsoft.

Google ❤️ Open Source for everyone.

Alibaba Open Source for everyone

Data-Driven Documents codes.

China tencent open source team.

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Remove unnecessary value assignment (IDE0059)

  • 4 contributors

This rule flags unnecessary value assignments. For example:

You can take one of the following actions to fix this violation:

If the expression on the right side of the assignment has no side effects, remove the expression or the entire assignment statement. This improves performance by avoiding unnecessary computation.

If the expression on the right side of the assignment has side effects, replace the left side of the assignment with a discard (C# only) or a local variable that's never used. Discards improve code clarity by explicitly showing the intent to discard an unused value.

The options for this specify whether to prefer the use of a discard or an unused local variable:

  • C# - csharp_style_unused_value_assignment_preference
  • Visual Basic - visual_basic_style_unused_value_assignment_preference

For information about configuring options, see Option format .

csharp_style_unused_value_assignment_preference

Visual_basic_style_unused_value_assignment_preference, suppress a warning.

If you want to suppress only a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

To disable the rule for a file, folder, or project, set its severity to none in the configuration file .

To disable all of the code-style rules, set the severity for the category Style to none in the configuration file .

For more information, see How to suppress code analysis warnings .

This rule flags unnecessary value assignments. For example, answer is unused in the following snippet:

  • Remove unused expression value (IDE0058)
  • Code style rules reference

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

SA – staticcheck

The SA category of checks, codenamed staticcheck , contains all checks that are concerned with the correctness of code.

SA1 – Various misuses of the standard library

Checks in this category deal with misuses of the standard library. This tends to involve incorrect function arguments or violating other invariants laid out by the standard library's documentation.

SA1000 - Invalid regular expression

Sa1001 - invalid template, sa1002 - invalid format in time.parse, sa1003 - unsupported argument to functions in encoding/binary.

The encoding/binary package can only serialize types with known sizes. This precludes the use of the int and uint types, as their sizes differ on different architectures. Furthermore, it doesn’t support serializing maps, channels, strings, or functions.

Before Go 1.8, bool wasn’t supported, either.

SA1004 - Suspiciously small untyped constant in time.Sleep

The time .Sleep function takes a time.Duration as its only argument. Durations are expressed in nanoseconds. Thus, calling time.Sleep(1) will sleep for 1 nanosecond. This is a common source of bugs, as sleep functions in other languages often accept seconds or milliseconds.

The time package provides constants such as time.Second to express large durations. These can be combined with arithmetic to express arbitrary durations, for example 5 * time.Second for 5 seconds.

If you truly meant to sleep for a tiny amount of time, use n * time.Nanosecond to signal to Staticcheck that you did mean to sleep for some amount of nanoseconds.

SA1005 - Invalid first argument to exec.Command

os/exec runs programs directly (using variants of the fork and exec system calls on Unix systems). This shouldn’t be confused with running a command in a shell. The shell will allow for features such as input redirection, pipes, and general scripting. The shell is also responsible for splitting the user’s input into a program name and its arguments. For example, the equivalent to

If you want to run a command in a shell, consider using something like the following – but be aware that not all systems, particularly Windows, will have a /bin/sh program:

SA1006 - Printf with dynamic first argument and no further arguments

Using fmt.Printf with a dynamic first argument can lead to unexpected output. The first argument is a format string, where certain character combinations have special meaning. If, for example, a user were to enter a string such as

and you printed it with

it would lead to the following output:

Similarly, forming the first parameter via string concatenation with user input should be avoided for the same reason. When printing user input, either use a variant of fmt.Print , or use the %s Printf verb and pass the string as an argument.

SA1007 - Invalid URL in net/url.Parse

Sa1008 - non-canonical key in http.header map.

Keys in http.Header maps are canonical, meaning they follow a specific combination of uppercase and lowercase letters. Methods such as http.Header.Add and http.Header.Del convert inputs into this canonical form before manipulating the map.

When manipulating http.Header maps directly, as opposed to using the provided methods, care should be taken to stick to canonical form in order to avoid inconsistencies. The following piece of code demonstrates one such inconsistency:

The easiest way of obtaining the canonical form of a key is to use http.CanonicalHeaderKey .

SA1010 - (*regexp.Regexp).FindAll called with n == 0 , which will always return zero results

If n >= 0 , the function returns at most n matches/submatches. To return all results, specify a negative number.

SA1011 - Various methods in the strings package expect valid UTF-8, but invalid input is provided

Sa1012 - a nil context.context is being passed to a function, consider using context.todo instead, sa1013 - io.seeker.seek is being called with the whence constant as the first argument, but it should be the second, sa1014 - non-pointer value passed to unmarshal or decode, sa1015 - using time.tick in a way that will leak. consider using time.newticker , and only use time.tick in tests, commands and endless functions, sa1016 - trapping a signal that cannot be trapped.

Not all signals can be intercepted by a process. Specifically, on UNIX-like systems, the syscall.SIGKILL and syscall.SIGSTOP signals are never passed to the process, but instead handled directly by the kernel. It is therefore pointless to try and handle these signals.

SA1017 - Channels used with os/signal.Notify should be buffered

The os/signal package uses non-blocking channel sends when delivering signals. If the receiving end of the channel isn’t ready and the channel is either unbuffered or full, the signal will be dropped. To avoid missing signals, the channel should be buffered and of the appropriate size. For a channel used for notification of just one signal value, a buffer of size 1 is sufficient.

SA1018 - strings.Replace called with n == 0 , which does nothing

With n == 0 , zero instances will be replaced. To replace all instances, use a negative number, or use strings.ReplaceAll .

SA1019 - Using a deprecated function, variable, constant or field

Sa1020 - using an invalid host:port pair with a net.listen -related function, sa1021 - using bytes.equal to compare two net.ip.

A net.IP stores an IPv4 or IPv6 address as a slice of bytes. The length of the slice for an IPv4 address, however, can be either 4 or 16 bytes long, using different ways of representing IPv4 addresses. In order to correctly compare two net.IP s, the net.IP.Equal method should be used, as it takes both representations into account.

SA1023 - Modifying the buffer in an io.Writer implementation

Write must not modify the slice data, even temporarily.

SA1024 - A string cutset contains duplicate characters

The strings.TrimLeft and strings.TrimRight functions take cutsets, not prefixes. A cutset is treated as a set of characters to remove from a string. For example,

will result in the string "word" – any characters that are 1, 2, 3 or 4 are cut from the left of the string.

In order to remove one string from another, use strings.TrimPrefix instead.

SA1025 - It is not possible to use (*time.Timer).Reset ’s return value correctly

Sa1026 - cannot marshal channels or functions, sa1027 - atomic access to 64-bit variable must be 64-bit aligned.

On ARM, x86-32, and 32-bit MIPS, it is the caller’s responsibility to arrange for 64-bit alignment of 64-bit words accessed atomically. The first word in a variable or in an allocated struct, array, or slice can be relied upon to be 64-bit aligned.

You can use the structlayout tool to inspect the alignment of fields in a struct.

SA1028 - sort.Slice can only be used on slices

The first argument of sort.Slice must be a slice.

SA1029 - Inappropriate key in call to context.WithValue

The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context. Users of WithValue should define their own types for keys.

To avoid allocating when assigning to an interface{} , context keys often have concrete type struct{} . Alternatively, exported context key variables’ static type should be a pointer or interface.

SA1030 - Invalid argument in call to a strconv function

This check validates the format, number base and bit size arguments of the various parsing and formatting functions in strconv .

SA2 – Concurrency issues

Checks in this category find concurrency bugs.

SA2000 - sync.WaitGroup.Add called inside the goroutine, leading to a race condition

Sa2001 - empty critical section, did you mean to defer the unlock.

Empty critical sections of the kind

are very often a typo, and the following was intended instead:

Do note that sometimes empty critical sections can be useful, as a form of signaling to wait on another goroutine. Many times, there are simpler ways of achieving the same effect. When that isn’t the case, the code should be amply commented to avoid confusion. Combining such comments with a //lint:ignore directive can be used to suppress this rare false positive.

SA2002 - Called testing.T.FailNow or SkipNow in a goroutine, which isn’t allowed

Sa2003 - deferred lock right after locking, likely meant to defer unlock instead, sa3 – testing issues.

Checks in this category find issues in tests and benchmarks.

SA3000 - TestMain doesn’t call os.Exit , hiding test failures

Test executables (and in turn go test ) exit with a non-zero status code if any tests failed. When specifying your own TestMain function, it is your responsibility to arrange for this, by calling os.Exit with the correct code. The correct code is returned by (*testing.M).Run , so the usual way of implementing TestMain is to end it with os.Exit(m.Run()) .

SA3001 - Assigning to b.N in benchmarks distorts the results

The testing package dynamically sets b.N to improve the reliability of benchmarks and uses it in computations to determine the duration of a single operation. Benchmark code must not alter b.N as this would falsify results.

SA4 – Code that isn't really doing anything

Checks in this category point out code that doesn't have any meaningful effect on a program's execution. Usually this means that the programmer thought the code would do one thing while in reality it does something else.

SA4000 - Binary operator has identical expressions on both sides

Sa4001 - &*x gets simplified to x , it does not copy x, sa4003 - comparing unsigned values against negative values is pointless, sa4004 - the loop exits unconditionally after one iteration, sa4005 - field assignment that will never be observed. did you mean to use a pointer receiver, sa4006 - a value assigned to a variable is never read before being overwritten. forgotten error check or dead code, sa4008 - the variable in the loop condition never changes, are you incrementing the wrong variable, sa4009 - a function argument is overwritten before its first use, sa4010 - the result of append will never be observed anywhere, sa4011 - break statement with no effect. did you mean to break out of an outer loop, sa4012 - comparing a value against nan even though no value is equal to nan, sa4013 - negating a boolean twice ( b ) is the same as writing b . this is either redundant, or a typo., sa4014 - an if/else if chain has repeated conditions and no side-effects; if the condition didn’t match the first time, it won’t match the second time, either, sa4015 - calling functions like math.ceil on floats converted from integers doesn’t do anything useful, sa4016 - certain bitwise operations, such as x ^ 0 , do not do anything useful, sa4017 - discarding the return values of a function without side effects, making the call pointless, sa4018 - self-assignment of variables, sa4019 - multiple, identical build constraints in the same file, sa4020 - unreachable case clause in a type switch.

In a type switch like the following

the second case clause can never be reached because T implements io.Reader and case clauses are evaluated in source order.

Another example:

Even though T has a Close method and thus implements io.ReadCloser , io.Reader will always match first. The method set of io.Reader is a subset of io.ReadCloser . Thus it is impossible to match the second case without matching the first case.

Structurally equivalent interfaces

A special case of the previous example are structurally identical interfaces. Given these declarations

the following type switch will have an unreachable case clause:

T will always match before V because they are structurally equivalent and therefore doSomething() ’s return value implements both.

SA4021 - x = append(y) is equivalent to x = y

Sa4022 - comparing the address of a variable against nil.

Code such as if &x == nil is meaningless, because taking the address of a variable always yields a non-nil pointer.

SA4023 - Impossible comparison of interface value with untyped nil

Under the covers, interfaces are implemented as two elements, a type T and a value V. V is a concrete value such as an int, struct or pointer, never an interface itself, and has type T. For instance, if we store the int value 3 in an interface, the resulting interface value has, schematically, (T=int, V=3). The value V is also known as the interface’s dynamic value, since a given interface variable might hold different values V (and corresponding types T) during the execution of the program.

An interface value is nil only if the V and T are both unset, (T=nil, V is not set), In particular, a nil interface will always hold a nil type. If we store a nil pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer: (T=*int, V=nil). Such an interface value will therefore be non-nil even when the pointer value V inside is nil.

This situation can be confusing, and arises when a nil value is stored inside an interface value such as an error return:

If all goes well, the function returns a nil p, so the return value is an error interface value holding (T=*MyError, V=nil). This means that if the caller compares the returned error to nil, it will always look as if there was an error even if nothing bad happened. To return a proper nil error to the caller, the function must return an explicit nil:

It’s a good idea for functions that return errors always to use the error type in their signature (as we did above) rather than a concrete type such as *MyError , to help guarantee the error is created correctly. As an example, os.Open returns an error even though, if not nil, it’s always of concrete type *os.PathError.

Similar situations to those described here can arise whenever interfaces are used. Just keep in mind that if any concrete value has been stored in the interface, the interface will not be nil. For more information, see The Laws of Reflection ( https://golang.org/doc/articles/laws_of_reflection.html) .

This text has been copied from https://golang.org/doc/faq#nil_error , licensed under the Creative Commons Attribution 3.0 License.

SA4024 - Checking for impossible return value from a builtin function

Return values of the len and cap builtins cannot be negative.

See https://golang.org/pkg/builtin/#len and https://golang.org/pkg/builtin/#cap .

SA4025 - Integer division of literals that results in zero

When dividing two integer constants, the result will also be an integer. Thus, a division such as 2 / 3 results in 0 . This is true for all of the following examples:

Staticcheck will flag such divisions if both sides of the division are integer literals, as it is highly unlikely that the division was intended to truncate to zero. Staticcheck will not flag integer division involving named constants, to avoid noisy positives.

SA4026 - Go constants cannot express negative zero

In IEEE 754 floating point math, zero has a sign and can be positive or negative. This can be useful in certain numerical code.

Go constants, however, cannot express negative zero. This means that the literals -0.0 and 0.0 have the same ideal value (zero) and will both represent positive zero at runtime.

To explicitly and reliably create a negative zero, you can use the math.Copysign function: math.Copysign(0, -1) .

SA4027 - (*net/url.URL).Query returns a copy, modifying it doesn’t change the URL

(*net/url.URL).Query parses the current value of net/url.URL.RawQuery and returns it as a map of type net/url.Values . Subsequent changes to this map will not affect the URL unless the map gets encoded and assigned to the URL’s RawQuery .

As a consequence, the following code pattern is an expensive no-op: u.Query().Add(key, value) .

SA4028 - x % 1 is always zero

Sa4029 - ineffective attempt at sorting slice.

sort.Float64Slice , sort.IntSlice , and sort.StringSlice are types, not functions. Doing x = sort.StringSlice(x) does nothing, especially not sort any values. The correct usage is sort.Sort(sort.StringSlice(x)) or sort.StringSlice(x).Sort() , but there are more convenient helpers, namely sort.Float64s , sort.Ints , and sort.Strings .

SA4030 - Ineffective attempt at generating random number

Functions in the math/rand package that accept upper limits, such as Intn , generate random numbers in the half-open interval [0,n). In other words, the generated numbers will be >= 0 and < n – they don’t include n . rand.Intn(1) therefore doesn’t generate 0 or 1 , it always generates 0 .

SA4031 - Checking never-nil value against nil

Sa5 – correctness issues.

Checks in this category find assorted bugs and crashes.

SA5000 - Assignment to nil map

Sa5001 - deferring close before checking for a possible error, sa5002 - the empty for loop ( for {} ) spins and can block the scheduler, sa5003 - defers in infinite loops will never execute.

Defers are scoped to the surrounding function, not the surrounding block. In a function that never returns, i.e. one containing an infinite loop, defers will never execute.

SA5004 - for { select { ... with an empty default branch spins

Sa5005 - the finalizer references the finalized object, preventing garbage collection.

A finalizer is a function associated with an object that runs when the garbage collector is ready to collect said object, that is when the object is no longer referenced by anything.

If the finalizer references the object, however, it will always remain as the final reference to that object, preventing the garbage collector from collecting the object. The finalizer will never run, and the object will never be collected, leading to a memory leak. That is why the finalizer should instead use its first argument to operate on the object. That way, the number of references can temporarily go to zero before the object is being passed to the finalizer.

SA5007 - Infinite recursive call

A function that calls itself recursively needs to have an exit condition. Otherwise it will recurse forever, until the system runs out of memory.

This issue can be caused by simple bugs such as forgetting to add an exit condition. It can also happen “on purpose”. Some languages have tail call optimization which makes certain infinite recursive calls safe to use. Go, however, does not implement TCO, and as such a loop should be used instead.

SA5008 - Invalid struct tag

Sa5009 - invalid printf call, sa5010 - impossible type assertion.

Some type assertions can be statically proven to be impossible. This is the case when the method sets of both arguments of the type assertion conflict with each other, for example by containing the same method with different signatures.

The Go compiler already applies this check when asserting from an interface value to a concrete type. If the concrete type misses methods from the interface, or if function signatures don’t match, then the type assertion can never succeed.

This check applies the same logic when asserting from one interface to another. If both interface types contain the same method but with different signatures, then the type assertion can never succeed, either.

SA5011 - Possible nil pointer dereference

A pointer is being dereferenced unconditionally, while also being checked against nil in another place. This suggests that the pointer may be nil and dereferencing it may panic. This is commonly a result of improperly ordered code or missing return statements. Consider the following examples:

Staticcheck tries to deduce which functions abort control flow. For example, it is aware that a function will not continue execution after a call to panic or log.Fatal . However, sometimes this detection fails, in particular in the presence of conditionals. Consider the following example:

Staticcheck will flag the dereference of x , even though it is perfectly safe. Staticcheck is not able to deduce that a call to Fatal will exit the program. For the time being, the easiest workaround is to modify the definition of Fatal like so:

We also hard-code functions from common logging packages such as logrus. Please file an issue if we’re missing support for a popular package.

SA5012 - Passing odd-sized slice to function expecting even size

Some functions that take slices as parameters expect the slices to have an even number of elements. Often, these functions treat elements in a slice as pairs. For example, strings.NewReplacer takes pairs of old and new strings, and calling it with an odd number of elements would be an error.

SA6 – Performance issues

Checks in this category find code that can be trivially made faster.

SA6000 - Using regexp.Match or related in a loop, should use regexp.Compile

Sa6001 - missing an optimization opportunity when indexing maps by byte slices.

Map keys must be comparable, which precludes the use of byte slices. This usually leads to using string keys and converting byte slices to strings.

Normally, a conversion of a byte slice to a string needs to copy the data and causes allocations. The compiler, however, recognizes m[string(b)] and uses the data of b directly, without copying it, because it knows that the data can’t change during the map lookup. This leads to the counter-intuitive situation that

will be less efficient than

because the first version needs to copy and allocate, while the second one does not.

For some history on this optimization, check out commit f5f5a8b6209f84961687d993b93ea0d397f5d5bf in the Go repository.

SA6002 - Storing non-pointer values in sync.Pool allocates memory

A sync.Pool is used to avoid unnecessary allocations and reduce the amount of work the garbage collector has to do.

When passing a value that is not a pointer to a function that accepts an interface, the value needs to be placed on the heap, which means an additional allocation. Slices are a common thing to put in sync.Pools, and they’re structs with 3 fields (length, capacity, and a pointer to an array). In order to avoid the extra allocation, one should store a pointer to the slice instead.

See the comments on https://go-review.googlesource.com/c/go/+/24371 that discuss this problem.

SA6003 - Converting a string to a slice of runes before ranging over it

You may want to loop over the runes in a string. Instead of converting the string to a slice of runes and looping over that, you can loop over the string itself. That is,

will yield the same values. The first version, however, will be faster and avoid unnecessary memory allocations.

Do note that if you are interested in the indices, ranging over a string and over a slice of runes will yield different indices. The first one yields byte offsets, while the second one yields indices in the slice of runes.

SA6005 - Inefficient string comparison with strings.ToLower or strings.ToUpper

Converting two strings to the same case and comparing them like so

is significantly more expensive than comparing them with strings.EqualFold(s1, s2) . This is due to memory usage as well as computational complexity.

strings.ToLower will have to allocate memory for the new strings, as well as convert both strings fully, even if they differ on the very first byte. strings.EqualFold, on the other hand, compares the strings one character at a time. It doesn’t need to create two intermediate strings and can return as soon as the first non-matching character has been found.

For a more in-depth explanation of this issue, see https://blog.digitalocean.com/how-to-efficiently-compare-strings-in-go/

SA9 – Dubious code constructs that have a high probability of being wrong

Checks in this category find code that is probably wrong. Unlike checks in the other SA categories, checks in SA9 have a slight chance of reporting false positives. However, even false positives will point at code that is confusing and that should probably be refactored.

SA9001 - Defers in range loops may not run when you expect them to

Sa9002 - using a non-octal os.filemode that looks like it was meant to be in octal., sa9003 - empty body in an if or else branch, sa9004 - only the first constant has an explicit type.

In a constant declaration such as the following:

the constant Second does not have the same type as the constant First. This construct shouldn’t be confused with

where First and Second do indeed have the same type. The type is only passed on when no explicit value is assigned to the constant.

When declaring enumerations with explicit values it is therefore important not to write

This discrepancy in types can cause various confusing behaviors and bugs.

Wrong type in variable declarations

The most obvious issue with such incorrect enumerations expresses itself as a compile error:

fails to compile with

Losing method sets

A more subtle issue occurs with types that have methods and optional interfaces. Consider the following:

This code will output

as EnumSecond has no explicit type, and thus defaults to int .

SA9005 - Trying to marshal a struct with no public fields nor custom marshaling

The encoding/json and encoding/xml packages only operate on exported fields in structs, not unexported ones. It is usually an error to try to (un)marshal structs that only consist of unexported fields.

This check will not flag calls involving types that define custom marshaling behavior, e.g. via MarshalJSON methods. It will also not flag empty structs.

SA9006 - Dubious bit shifting of a fixed size integer value

Bit shifting a value past its size will always clear the value.

For instance:

will always result in 0.

This check flags bit shifting operations on fixed size integer values only. That is, int, uint and uintptr are never flagged to avoid potential false positives in somewhat exotic but valid bit twiddling tricks:

SA9007 - Deleting a directory that shouldn’t be deleted

It is virtually never correct to delete system directories such as /tmp or the user’s home directory. However, it can be fairly easy to do by mistake, for example by mistakingly using os.TempDir instead of ioutil.TempDir , or by forgetting to add a suffix to the result of os.UserHomeDir .

in your unit tests will have a devastating effect on the stability of your system.

This check flags attempts at deleting the following directories:

  • os.UserCacheDir
  • os.UserConfigDir
  • os.UserHomeDir

SA9008 - else branch of a type assertion is probably not reading the right value

When declaring variables as part of an if statement (like in if foo := ...; foo { ), the same variables will also be in the scope of the else branch. This means that in the following example

x in the else branch will refer to the x from x, ok := ; it will not refer to the x that is being type-asserted. The result of a failed type assertion is the zero value of the type that is being asserted to, so x in the else branch will always have the value 0 and the type int .

The S category of checks, codenamed simple , contains all checks that are concerned with simplifying code.

S1 – Code simplifications

Checks in this category find code that is unnecessarily complex and that can be trivially simplified.

S1000 - Use plain channel send or receive instead of single-case select

Select statements with a single case can be replaced with a simple send or receive.

S1001 - Replace for loop with call to copy

Use copy() for copying elements from one slice to another. For arrays of identical size, you can use simple assignment.

S1002 - Omit comparison with boolean constant

S1003 - replace call to strings.index with strings.contains, s1004 - replace call to bytes.compare with bytes.equal, s1005 - drop unnecessary use of the blank identifier.

In many cases, assigning to the blank identifier is unnecessary.

S1006 - Use for { ... } for infinite loops

For infinite loops, using for { ... } is the most idiomatic choice.

S1007 - Simplify regular expression by using raw string literal

Raw string literals use backticks instead of quotation marks and do not support any escape sequences. This means that the backslash can be used freely, without the need of escaping.

Since regular expressions have their own escape sequences, raw strings can improve their readability.

S1008 - Simplify returning boolean expression

S1009 - omit redundant nil check on slices.

The len function is defined for all slices, even nil ones, which have a length of zero. It is not necessary to check if a slice is not nil before checking that its length is not zero.

S1010 - Omit default slice index

When slicing, the second index defaults to the length of the value, making s[n:len(s)] and s[n:] equivalent.

S1011 - Use a single append to concatenate two slices

S1012 - replace time.now().sub(x) with time.since(x).

The time.Since helper has the same effect as using time.Now().Sub(x) but is easier to read.

S1016 - Use a type conversion instead of manually copying struct fields

Two struct types with identical fields can be converted between each other. In older versions of Go, the fields had to have identical struct tags. Since Go 1.8, however, struct tags are ignored during conversions. It is thus not necessary to manually copy every field individually.

S1017 - Replace manual trimming with strings.TrimPrefix

Instead of using strings.HasPrefix and manual slicing, use the strings.TrimPrefix function. If the string doesn’t start with the prefix, the original string will be returned. Using strings.TrimPrefix reduces complexity, and avoids common bugs, such as off-by-one mistakes.

S1018 - Use copy for sliding elements

copy() permits using the same source and destination slice, even with overlapping ranges. This makes it ideal for sliding elements in a slice.

S1019 - Simplify make call by omitting redundant arguments

The make function has default values for the length and capacity arguments. For channels, the length defaults to zero, and for slices, the capacity defaults to the length.

S1020 - Omit redundant nil check in type assertion

S1021 - merge variable declaration and assignment, s1023 - omit redundant control flow.

Functions that have no return value do not need a return statement as the final statement of the function.

Switches in Go do not have automatic fallthrough, unlike languages like C. It is not necessary to have a break statement as the final statement in a case block.

S1024 - Replace x.Sub(time.Now()) with time.Until(x)

The time.Until helper has the same effect as using x.Sub(time.Now()) but is easier to read.

S1025 - Don’t use fmt.Sprintf("%s", x) unnecessarily

In many instances, there are easier and more efficient ways of getting a value’s string representation. Whenever a value’s underlying type is a string already, or the type has a String method, they should be used directly.

Given the following shared definitions

we can simplify

S1028 - Simplify error construction with fmt.Errorf

S1029 - range over the string directly.

Ranging over a string will yield byte offsets and runes. If the offset isn’t used, this is functionally equivalent to converting the string to a slice of runes and ranging over that. Ranging directly over the string will be more performant, however, as it avoids allocating a new slice, the size of which depends on the length of the string.

S1030 - Use bytes.Buffer.String or bytes.Buffer.Bytes

bytes.Buffer has both a String and a Bytes method. It is almost never necessary to use string(buf.Bytes()) or []byte(buf.String()) – simply use the other method.

The only exception to this are map lookups. Due to a compiler optimization, m[string(buf.Bytes())] is more efficient than m[buf.String()] .

S1031 - Omit redundant nil check around loop

You can use range on nil slices and maps, the loop will simply never execute. This makes an additional nil check around the loop unnecessary.

S1032 - Use sort.Ints(x) , sort.Float64s(x) , and sort.Strings(x)

The sort.Ints , sort.Float64s and sort.Strings functions are easier to read than sort.Sort(sort.IntSlice(x)) , sort.Sort(sort.Float64Slice(x)) and sort.Sort(sort.StringSlice(x)) .

S1033 - Unnecessary guard around call to delete

Calling delete on a nil map is a no-op.

S1034 - Use result of type assertion to simplify cases

S1035 - redundant call to net/http.canonicalheaderkey in method call on net/http.header.

The methods on net/http.Header , namely Add , Del , Get and Set , already canonicalize the given header name.

S1036 - Unnecessary guard around map access

When accessing a map key that doesn’t exist yet, one receives a zero value. Often, the zero value is a suitable value, for example when using append or doing integer math.

The following

can be simplified to

S1037 - Elaborate way of sleeping

Using a select statement with a single case receiving from the result of time.After is a very elaborate way of sleeping that can much simpler be expressed with a simple call to time.Sleep.

S1038 - Unnecessarily complex way of printing formatted string

Instead of using fmt.Print(fmt.Sprintf(...)) , one can use fmt.Printf(...) .

S1039 - Unnecessary use of fmt.Sprint

Calling fmt.Sprint with a single string argument is unnecessary and identical to using the string directly.

S1040 - Type assertion to current type

The type assertion x.(SomeInterface) , when x already has type SomeInterface , can only fail if x is nil. Usually, this is left-over code from when x had a different type and you can safely delete the type assertion. If you want to check that x is not nil, consider being explicit and using an actual if x == nil comparison instead of relying on the type assertion panicking.

ST – stylecheck

The ST category of checks, codenamed stylecheck , contains all checks that are concerned with stylistic issues.

ST1 – Stylistic issues

The rules contained in this category are primarily derived from the Go wiki and represent community consensus.

Some checks are very pedantic and disabled by default. You may want to tweak which checks from this category run , based on your project's needs.

ST1000 - Incorrect or missing package comment non-default

Packages must have a package comment that is formatted according to the guidelines laid out in https://github.com/golang/go/wiki/CodeReviewComments#package-comments .

ST1001 - Dot imports are discouraged

Dot imports that aren’t in external test packages are discouraged.

The dot_import_whitelist option can be used to whitelist certain imports.

Quoting Go Code Review Comments:

The import . form can be useful in tests that, due to circular dependencies, cannot be made part of the package being tested: package foo_test import ( "bar/testutil" // also imports "foo" . "foo" ) In this case, the test file cannot be in package foo because it uses bar/testutil , which imports foo . So we use the import . form to let the file pretend to be part of package foo even though it is not. Except for this one case, do not use import . in your programs. It makes the programs much harder to read because it is unclear whether a name like Quux is a top-level identifier in the current package or in an imported package.
  • dot_import_whitelist

ST1003 - Poorly chosen identifier non-default

Identifiers, such as variable and package names, follow certain rules.

See the following links for details:

  • https://golang.org/doc/effective_go.html#package-names
  • https://golang.org/doc/effective_go.html#mixed-caps
  • https://github.com/golang/go/wiki/CodeReviewComments#initialisms
  • https://github.com/golang/go/wiki/CodeReviewComments#variable-names
  • initialisms

ST1005 - Incorrectly formatted error string

Error strings follow a set of guidelines to ensure uniformity and good composability.

Error strings should not be capitalized (unless beginning with proper nouns or acronyms) or end with punctuation, since they are usually printed following other context. That is, use fmt.Errorf("something bad") not fmt.Errorf("Something bad") , so that log.Printf("Reading %s: %v", filename, err) formats without a spurious capital letter mid-message.

ST1006 - Poorly chosen receiver name

The name of a method’s receiver should be a reflection of its identity; often a one or two letter abbreviation of its type suffices (such as “c” or “cl” for “Client”). Don’t use generic names such as “me”, “this” or “self”, identifiers typical of object-oriented languages that place more emphasis on methods as opposed to functions. The name need not be as descriptive as that of a method argument, as its role is obvious and serves no documentary purpose. It can be very short as it will appear on almost every line of every method of the type; familiarity admits brevity. Be consistent, too: if you call the receiver “c” in one method, don’t call it “cl” in another.

ST1008 - A function’s error value should be its last return value

A function’s error value should be its last return value.

ST1011 - Poorly chosen name for variable of type time.Duration

time.Duration values represent an amount of time, which is represented as a count of nanoseconds. An expression like 5 * time.Microsecond yields the value 5000 . It is therefore not appropriate to suffix a variable of type time.Duration with any time unit, such as Msec or Milli .

ST1012 - Poorly chosen name for error variable

Error variables that are part of an API should be called errFoo or ErrFoo .

ST1013 - Should use constants for HTTP error codes, not magic numbers

HTTP has a tremendous number of status codes. While some of those are well known (200, 400, 404, 500), most of them are not. The net/http package provides constants for all status codes that are part of the various specifications. It is recommended to use these constants instead of hard-coding magic numbers, to vastly improve the readability of your code.

  • http_status_code_whitelist

ST1015 - A switch’s default case should be the first or last case

St1016 - use consistent method receiver names non-default, st1017 - don’t use yoda conditions.

Yoda conditions are conditions of the kind if 42 == x , where the literal is on the left side of the comparison. These are a common idiom in languages in which assignment is an expression, to avoid bugs of the kind if (x = 42) . In Go, which doesn’t allow for this kind of bug, we prefer the more idiomatic if x == 42 .

ST1018 - Avoid zero-width and control characters in string literals

St1019 - importing the same package multiple times.

Go allows importing the same package multiple times, as long as different import aliases are being used. That is, the following bit of code is valid:

However, this is very rarely done on purpose. Usually, it is a sign of code that got refactored, accidentally adding duplicate import statements. It is also a rarely known feature, which may contribute to confusion.

Do note that sometimes, this feature may be used intentionally (see for example https://github.com/golang/go/commit/3409ce39bfd7584523b7a8c150a310cea92d879d ) – if you want to allow this pattern in your code base, you’re advised to disable this check.

ST1020 - The documentation of an exported function should start with the function’s name non-default

Doc comments work best as complete sentences, which allow a wide variety of automated presentations. The first sentence should be a one-sentence summary that starts with the name being declared.

If every doc comment begins with the name of the item it describes, you can use the doc subcommand of the go tool and run the output through grep.

See https://golang.org/doc/effective_go.html#commentary for more information on how to write good documentation.

ST1021 - The documentation of an exported type should start with type’s name non-default

St1022 - the documentation of an exported variable or constant should start with variable’s name non-default, st1023 - redundant type in variable declaration non-default, qf – quickfix.

The QF category of checks, codenamed quickfix , contains checks that are used as part of gopls for automatic refactorings. In the context of gopls, diagnostics of these checks will usually show up as hints, sometimes as information-level diagnostics.

QF1 – Quickfixes

Qf1001 - apply de morgan’s law, qf1002 - convert untagged switch to tagged switch.

An untagged switch that compares a single variable against a series of values can be replaced with a tagged switch.

QF1003 - Convert if/else-if chain to tagged switch

A series of if/else-if checks comparing the same variable against values can be replaced with a tagged switch.

QF1004 - Use strings.ReplaceAll instead of strings.Replace with n == -1

Qf1005 - expand call to math.pow.

Some uses of math.Pow can be simplified to basic multiplication.

QF1006 - Lift if + break into loop condition

Qf1007 - merge conditional assignment into variable declaration, qf1008 - omit embedded fields from selector expression, qf1009 - use time.time.equal instead of == operator, qf1010 - convert slice of bytes to string when printing it, qf1011 - omit redundant type from variable declaration, qf1012 - use fmt.fprintf(x, ...) instead of x.write(fmt.sprintf(...)).

superfluous-else-return (RET505) #

Derived from the flake8-return linter.

Fix is sometimes available.

What it does #

Checks for else statements with a return statement in the preceding if block.

Why is this bad? #

The else statement is not needed as the return statement will always break out of the enclosing function. Removing the else will reduce nesting and make the code more readable.

Use instead:

PhpStorm 2024.1 Help

Code inspection: unnecessary 'return' statement.

Reports an unnecessary return statement, that is, a return statement that returns no value and occurs just before the function would have "fallen through" the bottom. These statements may be safely removed.

Suppress an inspection in the editor

Click the arrow next to the inspection you want to suppress and select the necessary suppress action.

IMAGES

  1. return statement in C++ with Examples

    unnecessary variable assignment before return statement

  2. Python return statement

    unnecessary variable assignment before return statement

  3. Return Statement in C

    unnecessary variable assignment before return statement

  4. PPT

    unnecessary variable assignment before return statement

  5. 1.4. Expressions and Assignment Statements

    unnecessary variable assignment before return statement

  6. Python return statement

    unnecessary variable assignment before return statement

VIDEO

  1. Assignment Statement and Constant Variable

  2. Use Destructuring Assignment to Pass an Object as a Function's Parameters (ES6) freeCodeCamp

  3. 6 storing values in variable, assignment statement

  4. Assignment with a Returned Value (Basic JavaScript) freeCodeCamp tutorial

  5. R variable assignment

  6. C++ Variables, Literals, an Assignment Statements [2]

COMMENTS

  1. Implement autofix for RET504 Unnecessary variable assignment before

    A fixer for RET504 Unnecessary variable assignment before 'return' statement would be nice. def random_zone(): - random_zone = f'{uts.random_string()}.{uts.random ...

  2. Local variables before return statements, does it matter?

    There is actually a SonarQube rule inherited from PMD called Unnecessary Local Before Return that talks about this. It says: Avoid unnecessarily creating local variables. This rule was later replaced by SSLR rule Variables should not be declared and then immediately returned or thrown, which maintains the same position:. Declaring a variable only to immediately return or throw it is a bad ...

  3. flake8-return · PyPI

    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 ...

  4. RET504 false-positive when variable built up with assignments and

    main.py:15:12: RET504 Unnecessary variable assignment before return statement. ... # RET504: Unnecessary variable before return (ugly) # suppress what appears to be false-positives with these checks 'RET504', 'RET505', 'RET506', 'RET507', 'RET508', See many examples with similar chaining-style assignment with conditionals that we've touched on ...

  5. GitHub

    R504 unnecessary variable assignment before return statement. def x (): a = 1 # some code that not using `a` print ('test') return a # error! ... 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.

  6. unnecessary-assign (RET504)

    unnecessary-assign (RET504)# Derived from the flake8-return linter. Fix is always available. What it does# Checks for variable assignments that immediately precede a return of the assigned variable. Why is this bad?# The variable assignment is not necessary, as the value can be returned directly. Example#

  7. How do I avoid a useless return in a Java method?

    Create an array of integers 0 .. range-1. Set all the values to 0. Perform a loop. In the loop, generate a random number. Look in your list, at that index, to see if the value is 1 If it is, break out of the loop. Otherwise, set the value at that index to 1. Count the number of 1s in the list, and return that value.

  8. no-useless-return

    A return; statement with nothing after it is redundant, and has no effect on the runtime behavior of a function. This can be confusing, so it's better to disallow these redundant statements. Rule Details. This rule aims to report redundant return statements.. Examples of incorrect code for this rule:

  9. Return statement assigns local variable

    Return statement assigns local variable. ¶. - maintainability. - readability. - external/cwe/cwe-563. - javascript-security-and-quality.qls. Click to see the query in the CodeQL repository. Assigning a local variable in a return statement is useless, since the local variable will go out of scope immediately and its new value is lost.

  10. False-positive RET504 "Unnecessary variable assignment before `return

    $ ruff test_ruff_ret_504.py Found 1 error(s). test_ruff_ret_504.py:8:12: RET504 Unnecessary variable assignment before `return` statement. ... actionless changed the title False-positive RET504 False-positive RET504 "Unnecessary variable assignment before return statement" Dec 19, 2022. Copy link Contributor. squiddy commented Dec 19, 2022.

  11. The flake8-return from afonasev

    afonasev / flake8-return Goto Github PK View Code? Open in Web Editor NEW 61.0 3.0 71.0 187 KB. Flake8 plugin for return expressions checking. License: MIT License. Python 96.90% Makefile 3.10% flake8-plugin. Introduction · People · Discuss; flake8-return's Introduction

  12. IDE0059

    C#. Copy. // IDE0059: value written to 'v' is never // read, so assignment to 'v' is unnecessary. int v = Compute(); v = Compute2(); You can take one of the following actions to fix this violation: If the expression on the right side of the assignment has no side effects, remove the expression or the entire assignment statement.

  13. False-Positive R504 in non-trivial if-else Block #132

    flake8-return version used, if any: 1.2.0; Python version, if any: 3.10; Operating System: Windows 11; Description. The application of R504 unnecessary variable assignment before return statement seems wrong here. I've specifically not inlined my return statement in order to have a single return in this "complicated" if-else block.

  14. Checks

    This is commonly a result of improperly ordered code or missing return statements. Consider the following examples: func fn (x * int) ... assigning to the blank identifier is unnecessary. Before: for _ = range s {} x, _ = someMap [key] _ = <-ch. After: for range s {} x = someMap ... Merge variable declaration and assignment. Before: var x uint ...

  15. superfluous-else-return (RET505)

    superfluous-else-return (RET505)# Derived from the flake8-return linter.. Fix is sometimes available. What it does#. Checks for else statements with a return statement in the preceding if block.. Why is this bad?# The else statement is not needed as the return statement will always break out of the enclosing function. Removing the else will reduce nesting and make the code more readable.

  16. "Unnecessary variable assignment before return " is too eager #1233

    x() arbitrary function call can have side-effects. This is a dirt simple example, but it's not hard to imagine sequences of statements which would mutate bar's value between the assignment and the return, even if there aren't direct references to bar itself (which seems to be the current heuristic).. Thus, it seems to me to be too eager to flag this, so long as there are potentially side ...

  17. Code Inspection: Unnecessary 'return' statement

    Reports an unnecessary return statement, that is, a return statement that returns no value and occurs just before the function would have "fallen through" the bottom. These statements may be safely removed. Suppress an inspection in the editor. Place the caret at the highlighted line and press Alt+Enter or click .. Click the arrow next to the inspection you want to suppress and select the ...

  18. Unecessary assignment of a value c# when using out

    4. Just don't set the initial value. This is perfectly valid code : string errorMessage; var valid = IsValid(out errorMessage); Or use. var valid=IsValid(out var errorMessage); The compiler knows that the variable is used as an out parameter and will get a value unless an exception is thrown. On the other hand, IsValid has to store a value in ...

  19. False positive on R504 · Issue #3 · afonasev/flake8-return

    Milestone. No milestone. Development. No branches or pull requests. 2 participants. Date you used flake8-return: 2019-05-16 flake8-return version used, if any: 1.0.0 Python version, if any: 3.7.1 Operating System: Debian Description The R504 doesn't detect that the variable is conditionally modified prior to return.

  20. Using variable before assigment error when using lists

    Using variable 'criteria_names' before assignment pylint ... It probably has something to do with the fact that you don't return criteria_names like all the other lists. - Barmar. Jan 12, 2019 at 16:43 ... Making statements based on opinion; back them up with references or personal experience.