by crazygringo · 12y ago · 0 comments
To me personally, testing for 'truthy' and 'falsy' values, or relying on exceptions rather than checking values in advance, feels like sloppy and imprecise programming.
A string being empty or not, or an array having items or not, or a boolean being true or false, are all qualitatively totally different things to me -- and just because Python can treat them the same, doesn't mean a programmer should take advantage of that fact. Sometimes it's possible to over-simplify things in a way that obfuscates instead of clarifying.
When I read:
if name and pets and owners
I have no intuitive idea of what that means, of what's going on in the program. When I read if name != '' and len(pets) > 0 and owners != {}
I understand it exactly.But by this point, I've come to understand that, for a lot of people, it seems to be the opposite. It seems to be more of a philosophical difference, not right/wrong.
if name != '' and len(pets) > 0 and owners != {}
would tell you that name is a non-empty string, pets has values, and owners is a non-empty dict (except it doesn't work, as pdonis noticed).But Python allows immoral implicit conversions, so that's not what that line means! If name is a function, pets is the value '7' and owners is a list, the test passes.
if name and pets and owners
Would pass as well, but it has the advantage of not implying it does more than it does: all you can infer from the test passing is that none of name,pets,owners are special falsy values.If you actually wanted to test what the longer line is implying, you'd write something like
if isinstance(name, str) and isinstance(pets, list) and isinstance(owners, set) and name and pets and owners
(don't do this, it violates duck-typing and LBYL)No, it doesn't tell you that. {} denotes an empty dict, not an empty set; and an empty set will return True for owners != {}, not False. As I noted in another post upthread, you would need to write
len(owners) > 0
to get the correct semantics, making owners indistinguishable from pets even if they are different container types. If you really wanted to make all the types clear, you would need to include the isinstance tests.While this is true, I think it's important to keep in mind that a big benefit of being able to handle a situation programatically in different ways is that you, as a programmer, are more able to accurately describe intent.
For example, I think it's foolish to always catch exceptions instead of checking beforehand (look-before-you-leap). However, being able to do either allows me to more accurately represent the intent of a statement. Blindly following rules is almost always sure to lead to poor decisions.
If I'm retrieving an element from an array and I know that for the majority of possible application states there will be an element there, I can just access it, and handle an exception (because it's an "exceptional" case). However if I'm expecting that it could go either way in typical circumstances, then I might more explicitly check the index in the array to illustrate my intent that yes, there are two distinct paths here and that is how the program's control flows naturally.
Of course all of these things are only worthwhile if the reader can see and interpret them as purposeful decisions rather than coincidence. Conveying that is something else entirely.
My response to this is, why do you care what their types are? What the statement is saying, conceptually, is "if there's a name and there's pets and there's owners, do this". Why should I have to explicitly tell the language how to tell whether there's a name and there's pets and there's owners, when it already knows that? To me that's just extra verbosity for no good reason. Do you really care that name is a string but pets and owners are containers? (And even if you do, isn't that evident from the variable names anyway? Good naming conventions can do a lot of the work of clarifying what's going on while keeping the code compact.)
Exactly. It's philosophically different from other languages, but it's standard in Python.
name = None
instead of name = ''
Then the second conditional would fail, whereas the first would still be fine.If you are using truthy/falsey values, I think it can be a code smell that you are not doing enough to catch invalid values up front or should normalize the values closer to their creation point.
if something:
do_this()
elif something_else:
do_that()
else:
# hope we don't end up here
raise UserWarning('We shouldn't have ended up here')Relying on implicit conversions is just sloppy. What if that variable was never supposed to be None in the first place. Better with an exception than continuing with corrupt data.
Remember another python motto: Explicit is better than implicit.
`len` blows up on None, so this blows up completely instead of just failing.
> Relying on implicit conversions is just sloppy.
There is no implicit conversion. Truthiness is a protocol, it does not convert anything anywhere.
That's the whole point! As I said, Better with an exception than continuing with corrupt data. Or maybe I should say unsupported data type rather than corrupt data.
None and '' are two completely different things, and could mean different thing sin the context of the application. It's quite likely that choosing either is a conscious choice of the programmer.
name is None
since None is a unique distinct valueedit: didn't notice at first that you wrote an assignment, not a comparison
The reason for this is that 'is' tests to see if both operands are the same object; it's not a test of equivalence on any level.
There is only ever one instance of None, and you simply get or create references to it. Likewise, there is only one instance of integers up to 256 (presumably a performance optimization for small loops, indexes, etc.). Integers after 256 get separate instances each time, so 'is' fails after that point.
A lot of newcomers to Python come across the 'is None' construct and make assumptions about what 'is' does; the worst part is that they're often correct, and the behaviour becomes difficult to track down when it changes.
Really? Containers of different types have a len method; which type of container is pets? The line you wrote doesn't tell you. And is owners supposed to be a set? If so, your comparison to an empty dict will give the wrong semantics if owners is an empty set (owners != {} will return True for an empty set, not False). You would have to write
len(owners) > 0
to get the correct semantics. Which, of course, already obscures the type of owners, just as the type of pets is obscured.In short, your suggested "improvement" over idiomatic Python still obfuscates rather than clarifying.
> if name and pets and owners
>I have no intuitive idea of what that means, of what's going on in the program.
I agree with you, when I read that I think if name and pets and owners, what? All equal each other? Seems like an unfinished statement.