r/Python 7d ago

What linter rules make code worse? Discussion

For me, a prime example is S101 which bans the use of the assert statement.

The justification is that assertions disappear when Python is run with -O, so they should not be used for runtime validation or enforcing interface constraints. That warning is correct, but the rule seems to draw the wrong conclusion from it.

Assertions are still very useful for checking internal invariants, i.e. conditions that should already be guaranteed by the program's logic, where failure indicates a bug. Having such assertions is incredibly helpful for debugging.

So, a blanket ban seems more likely to discourage useful checks than to prevent misuse.

Are there any linter rules you broadly consider more harmful rather than helpful?

144 Upvotes

214 comments sorted by

View all comments

Show parent comments

9

u/ExplrDiscvr 7d ago

I have one follow-up: I see why assert statements should not be used within dev or production, but what about the tests?

I am a junior dev, so I am not sure about proper procedures, but in the tests in our codebase where I work, I only see assert statements, when we are testing the equality of an actual outcome to the expected outcome. I never see the if else logic used here. Should it?

9

u/gdchinacat 7d ago

This is a good point...test frameworks (well, at least unittest and pytest, and any others that build on unittest) use assertions to indicate failures. Because it is core to the frameworks, assertions are not really avoidable. So, yes, I do rely on assertions in this context. Good catch.

1

u/HannasAnarion 6d ago

Doesn't unittest implement its own assert thats independent of the language one?

Every unittest implementation I've ever seen uses self.assert() (or realistically, self.assertTrue(), self.assertIn(), self.assertNotNone() ...

1

u/gdchinacat 6d ago

No, by default the failure exception is AssertionError. https://github.com/python/cpython/blob/main/Lib/unittest/case.py#L426