loading...

Discussion on: 3 Tricky Python Nuances

Collapse
ramalhoorg profile image
Luciano Ramalho ☔ 🐍 ⒼⓄ

Good points about lists and default argument. I disagree with your take on is v ==. It is an anti-pattern to test booleans with is or ==. They are already booleans, so there is no reason to write if x is True:, just write if x:.

Also, Python is happy to use any value in boolean contexts, which makes it even less common to handle booleans explicitly as you suggest.

The only really common case of using is in Python code is to test for None, as in if x is None:. This is clear, explicit, and performant, because None is singleton, and there is no overloading for the is operator, so it is faster than == which can be overloaded via the __eq__ special method. Other than that, uses cases that actually require or recommend the use of the is operator are extremely rare.

Collapse
thejessleigh profile image
jess unrein Author

I have worked in a couple teams where my engineering managers had a real stick in their craw about always using is comparators with booleans to the point of rejecting PRs that didn't follow this pattern. But you may be right that the more Pythonic way would be to write if x: when checking for Truth. It's a pattern that I've had drilled into my head that might, in fact, not be as idiomatically Pythonic as I had been led to believe.

However, to your point, if you want to check that something is explicitly False (as opposed to something being False or None) it makes sense to me to use an explicit comparator rather than relying on if not x: as if not reads None as a falsey value. Granted, the use case here is pretty narrow, so it's not super useful.

Thank you for the clarification!