0

Consider this small function:

def test():
    x = 1
    x = 2
    x = 3
    return x + 1

Apparently, the first two assignments to x have no effect here and can be removed. Yet surprisingly, pylint/flake8/ruff don't produce any warnings about it (at least with the default config). Is there any particular reason for this?

8
  • 1
    looking at the docs pylint.pycqa.org/en/stable/user_guide/messages/… this case isn't covered at the moment. maybe do a feature request instead of an SO question? Commented Oct 27 at 12:09
  • @BendingRodriguez As I mentioned in my comment to your (now deleted) answer, I didn’t mean pylint specifically. It seems that the three most popular Python linters ignore this issue, so there might be a deeper reason behind it. Commented Oct 27 at 14:34
  • I say no, because a tool like pylint could check if you have multiple variable assignments with constant values and tell you thats useless, it could also detect if you assign multiple function calls which should be undetected since it could follow some actual purpose. but as you already stated, it doesnt alert in both cases which makes no sense Commented Oct 27 at 14:38
  • 1
    @BendingRodriguez It’s not intentional, it happens by accident. Commented Oct 27 at 15:02
  • 1
    @Ramrab Actually, no, linters do much more than just syntax checking. In fact, you don't need any linters to check syntax, you can use the interpreter itself for that. Commented Oct 27 at 16:42

1 Answer 1

1

My guess is that such repeated assignments are ignored by most linters because they may have side effects that may be difficult to detect, e.g.:

def test():
    x = do_stuff()
    x = do_other_stuff()
    return x + 1

Here, the values are not simple scalars, but the results of running some functions. So the first statement may or may not be redundant.

For linters to be more useful in such cases, it's better to use distinct variable names for intermediate results instead of repeatedly assigning values to the same variable.

Sign up to request clarification or add additional context in comments.

7 Comments

but thats a different case than the sample in your question. the difference from assigning a constant multiple times to assigning functions couldnt be bigger
That's the point of my answer, still both are multiple assignment cases
but a tool like pylint could distinguish between these Im shure
This should still generate a warning, since there's no need to assign the result in the first line.
@KellyBundy I can't think of a good reason for that. It sounds like maybe they should be using a context manager.
Remember, linters are for detecting poor coding style. That weird requirement definitely counts.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.