Search code examples
pythonpylintpython-assignment-expression

Pylint is not suggesting the walrus operator. Why?


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?


Solution

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