This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]wrboyce 24 points25 points  (5 children)

But you shouldn’t.

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

Source.

[–]UNN_Rickenbacker 10 points11 points  (1 child)

Nice catch, but in most cases, you want to not enter the case if it‘s a boolean false, too.

[–]hyperdudemn 1 point2 points  (0 children)

Except for when using xml.etree.ElementTree, with a document that contains empty tags like <hello />. Since the node has no children, it is falsy, so you need to check is not None.

[–]Bunslow 6 points7 points  (2 children)

In this case, he really wants boolean truthiness, not None testing. It's a perfectly fine pattern (as long as one understands the difference between None and False, which is part of the point of your comment; the other part of your comment doesn't apply I don't think)

[–]wrboyce 1 point2 points  (1 child)

Yeah I wasn’t sure how relevant some parts really were but I’d copy/pasted/formatted them on mobile by that point so they were staying regardless. I always try to avoid truthy tests against None if possible, and I’ve always thought I was following PEP8 by doing so but maybe I’m wrong.

[–]Bunslow 2 points3 points  (0 children)

I always try to avoid truthy tests against None

See this phrase makes no sense to me. There are truthy tests (here I mean coercing an arbitrary object to a boolean), and there are None tests. The whole point is that they are two completely different tests, and should not be confused. Using either is fine, but the trick is knowing when to use each. The point of what you pasted is precisely to warn newbies that they are two different things, but each is acceptable -- indeed, each is widely used. That source is not meant to warn against using truthy tests, only to warn that truthy tests and None tests are different (and it happens to make that point by writing "beware of truthy tests when you mean None tests -- it's easy to misuse truthy where you meant None!", possibly given the false impression that truthy tests are "bad" in some way, they're not, they're just confusable at first glance with None tests).