4 ms·
I think part of the reasoning behind the truthy / falsy mechanic is that it's more robust. If, for whatever reason, we did: name = None instead of name =
by andrewfong 13y ago
I think part of the reasoning behind the truthy / falsy mechanic is that it's more robust. If, for whatever reason, we did:
name = None
instead of
name = ''
Then the second conditional would fail, whereas the first would still be fine.
- riquito 13y agoIn this particular case, you want to write name is None since None is a unique distinct value edit: didn't notice at first that you wrote an assignment, not a comparison
- danudey 13y agoNote that 'is' in Python is kind of tricky. None is None, and any value==None is also None. 1 is 1, and 100 is 100; 256 is 256 but 257 is not 257, and "test" is not "test". 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.
- prawks 13y agoSee my response as well, but it depends on your intent. 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.
- collyw 13y agoThe computer sees None and '' as different. But the users of my database at work just see a blank entry. As far as they are concerned, they are the same. For that reason it can be useful to have the code treat them the same.
- jfischer 13y agoI've personally run into problems when I don't do exact comparisons with True and False. For example, I've forgotten to return a value in one path of a function/method, and then tried to use the result in an if statement in the style recommended by the OP (e.g. if fcall(): do something). After being bitten several times by this, I always do explicit comparisons.
- beagle3 13y agoSo you never use "else"? Else is the mother of inexact comparisons.
- jfischer 13y agoIn this particular situation, there was no else. I probably added an else clause with an assert return_value == False, as the function call was a virtual dispatch that could have many implementations. Of course, I wouldn't do that for every if/then/else statement in my code. In general, I'd prefer a stricter language that only permitted a boolean as a condition in the IF statement, avoiding this problem altogether. 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.
- aaren 13y agoUse the else to let you know that something is going wrong, using raise or exit() or some die() function: 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')
- beagle3 13y agoBut the discussion is about truthy values and inexact comparisons - avoiding inexact comparisons and having an else means: if something==True: do_this() elif something==False: do_that() else: raise UserWarning("Shouldn't be here") Which is a code smell to me. What I would do is: assert isinstance(something, boolean), "Shouldn't happen" do_this() if something else do_that() (replace assert with something else if you want it not to be optimized away with -O; assert is a debug-only construct in Python. Or just drop the assert altogether. In most places, I would - there's no end to the amount of validation you could do, and most of it is unnecessary)
- Too 13y agoChecking for empty strings can be done with len(mystring)==0 for this reason. In many other languages this method is standard and recommended practice. 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.
- jessaustin 13y agoIf you need to differentiate between the empty string and None, you can, but in most situations the difference isn't important. E.g., would you ever actually display the values differently? Exaggerated explicitness can be misleading. E.g., if a year from now someone is making some changes, should they really be distracted by the fact that you've used 3 different if/else cases for the same semantic result?
- masklinn 13y ago> Checking for empty strings can be done with len(mystring)==0 for this reason. `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.
- Too 13y ago> `len` blows up on None, so this blows up completely instead of just failing 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.
- danudey 13y agoAt the point where you are doing your validation (or where you are doing the actual work with the variable) you can make that decision. It's entirely possible that upstream code is content with any type as long as it's coercible. A lot of Python code just wants an iterable, for example, or something that can be coerced to a string. It's definitely possible to have a situation where you need a string specifically (or an integer specifically), but it's generally better to have your code coerce the data whenever possible so as to allow for more logical code. e.g. 's.send(str(object))' (if object has a relevant __str__()) makes perfect sense in code. You don't necessarily need a string, you just need something that can behave as a string in a sensible manner. You also end up with scenarios where None is a 'valid value' in e.g. the SQL sense of 'value not specified'; for example, company_name might be '' (empty string provided) or None (no value provided); either way company_name is Falsey, and your logic should work the same.