pylint icon indicating copy to clipboard operation
pylint copied to clipboard

too-many-try-statements should exclude `pass` statements if required by Python

Open ColinKennedy opened this issue 1 year ago • 2 comments

Current problem

I have code like this

try:
    with open("blah.txt", "a", encoding="ascii"):
        pass
except exceptions_to_catch:
    # do stuff

The too-many-try-statements optional checker flags this as 2 statements, which is technically true, but the second statement, pass, is there only because the with block will cause SyntaxError without it.

Desired solution

It probably isn't a good idea to completely ignore any/all pass statements, though that would be the easiest way to solve this, but the check should at least ignore pass when it's required to by Python.

A more judicious approach would be "ignore the second statement if all of these are true:

  • The second statement is pass
  • The previous statement is a Python control flow statement like if ...:, with ...:, while ...:, or the like.
  • There are no other statements

Or something along those lines

Additional context

No response

ColinKennedy avatar Feb 08 '24 02:02 ColinKennedy

Sounds reasonable, especially since the default for --max-try-statements is 1.

It probably isn't a good idea to completely ignore any/all pass statements

I'm not even opposed to that. Are there realistic cases of people using pass to do something other than complete a for / while / with / else?

jacobtylerwalls avatar Feb 10 '24 15:02 jacobtylerwalls

Are there realistic cases of people using pass to do something other than complete a for / while / with / else?

None that I can think of. There could be code like

pass
foo = 8

pass
pass

But that code would already be pretty weird

ColinKennedy avatar Feb 10 '24 18:02 ColinKennedy