3 ms·
> if user is None: > if balance is None: > if credit is not None Why are people so obsessed with None? The explicit check is usually unnecessary. Just check di
by PurpleRamen 3y ago
> if user is None:
> if balance is None:
> if credit is not None
Why are people so obsessed with None? The explicit check is usually unnecessary. Just check directly.
if user:
if balance:=user.get_balance():
if credit:=balance.credit_amount():
discount_program = choose_discount(credit)
- mickeyp 3y agoBecause if something can return None, you should explicitly check for that, to avoid truthy/falsy gotchas [1]. [1] https://www.inspiredpython.com/article/truthy-and-falsy-gotchas https://www.inspiredpython.com/article/truthy-and-falsy-gotc...
- PurpleRamen 3y agoNo, you should not. Checking for None is relevant when you care about the case where it's important. But that doesn't mean every case is one. In the example here, all we care is if we can do something, and everything else doesn't matter. Which is also the reason why I could shortened credit from two checks to one.
- infecto 3y agoWalrus is great but your example of nesting 3 deep looks just as terrible as the original example. As for being obsessed with None. I usually lean towards it when no type has been provided like in the example. I think its appropriate when we are expecting it to be a None just to miss any traps further down the road. Just like typing in Python, you don't have to do it but I find it eliminates issues later on and makes it easier for others to read.