3

I was going to ask if there is a pylint-style code analyzer capable of suggesting the use of the := operator in places were it might improve the code. However, it looks like such test has been added to the pylint two years ago -> github PR (merged).

Anyway I never saw such suggestion, not even for this example like in the linked PR:

x = 2
if x:
    print(x)

# -----
# if (x := 2):
#    print(x)
# -----

This feature is available since Python 3.8. (I'm using recent Python and pylint versions.) I though I have to enable it somehow, but the help says:

--py-version <py_version> Minimum Python version to use for version dependent checks. Will default to the version used to run pylint.

What is wrong? Why there is no consider-using-assignment-expr from pylint?

6
  • 5
    You're not going to find this, because it does not improve the code. Your first example is better programming. The walrus operator was added late because it is controversial. Commented Sep 15, 2023 at 19:13
  • 2
    It isn't enabled by default (moved to extension and disabled in this PR). And I'd say that usually this change is not what you want: walrus is handy mostly in elif branches (to avoid nesting and extensive computations) or while (when it's used like for but on something that is not iterable).
    – STerliakov
    Commented Sep 15, 2023 at 21:51
  • 5
    To those who VTC: this question is not opinion-based at all. It asks a very self-contained question about pylint behavior (namely - why doesn't the linter fail a rule check on given code), which can be answered as is based on facts and code history.
    – STerliakov
    Commented Sep 15, 2023 at 21:52
  • @STerliakov: That change was for augmented assignments (like +=), not assignment expressions. Much as I dislike it, consider-using-assignment-expr is enabled by default in the codestyle extension, as long as you enable the extension itself. Commented Sep 15, 2023 at 22:39
  • consider-using-augmented-assignment is disabled by default even if you enable the extension. Strangely, this appears to have nothing to do with the fact that changing a = a+b to a += b can change the meaning of the line. Nobody brought that fact up in any of the discussion I can see surrounding the change. Commented Sep 15, 2023 at 22:40

1 Answer 1

3

The consider-using-assignment-expr check in pylint can be enabled by Adding the following line to your pylint configuration file. I am using a configuration file named pylint.toml:

[tool.pylint.main]
load-plugins="pylint.extensions.code_style"

Then you can run the linter using pylint --rcfile <config_file> <python_file>.

See here for more instructions. Note that I am using Python 3.11, and Pylint 2.17, but the check should be available since Python 3.8.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.