Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The advice isn't that you should never <strong>use</strong> <code>True</code>, <code>False</code>, or <code>None</code>. It's just that you shouldn't use <code>if x == True</code>.</p> <p><code>if x == True</code> is silly because <code>==</code> is just a binary operator! It has a return value of either <code>True</code> or <code>False</code>, depending on whether its arguments are equal or not. And <code>if condition</code> will proceed if <code>condition</code> is true. So when you write <code>if x == True</code> Python is going to first evaluate <code>x == True</code>, which will become <code>True</code> if <code>x</code> was <code>True</code> and <code>False</code> otherwise, and then proceed if the result of that is true. But if you're expecting <code>x</code> to be either <code>True</code> or <code>False</code>, why not just use <code>if x</code> directly!</p> <p>Likewise, <code>x == False</code> can usually be replaced by <code>not x</code>.</p> <p>There are some circumstances where you might want to use <code>x == True</code>. This is because an <code>if</code> statement condition is "evaluated in boolean context" to see if it is "truthy" rather than testing exactly against <code>True</code>. For example, non-empty strings, lists, and dictionaries are all considered truthy by an if statement, as well as non-zero numeric values, but none of those are equal to <code>True</code>. So if you want to test whether an arbitrary value is <strong>exactly</strong> the value <code>True</code>, not just whether it is truthy, when you would use <code>if x == True</code>. But I almost never see a use for that. It's so rare that if you <em>do</em> ever need to write that, it's worth adding a comment so future developers (including possibly yourself) don't just assume the <code>== True</code> is superfluous and remove it.</p> <hr> <p>Using <code>x is True</code> instead is actually worse. You should never use <code>is</code> with basic built-in immutable types like booleans (<code>True</code>, <code>False</code>), numbers, and strings. The reason is that for these types we care about <strong>values</strong>, not <strong>identity</strong>. <code>==</code> tests that values are the same for these types, while <code>is</code> always tests identities.</p> <p>Testing identities rather than values is bad because an implementation could theoretically construct new boolean values rather than go find existing ones, leading to you having two <code>True</code> values that have the same value but are stored in different placed in memory and have different identities. In practice I'm pretty sure <code>True</code> and <code>False</code> are always re-used by the Python interpreter so this won't happen, but that's really an implementation detail. This issue trips people up all the time with strings, because short strings and literal strings that appear directly in the program source are recycled by Python so <code>'foo' is 'foo'</code> always returns <code>True</code>. But it's easy to construct the same string 2 different ways and have Python give them different identities. Observe the following:</p> <pre><code>&gt;&gt;&gt; stars1 = ''.join('*' for _ in xrange(100)) &gt;&gt;&gt; stars2 = '*' * 100 &gt;&gt;&gt; stars1 is stars2 False &gt;&gt;&gt; stars1 == stars2 True </code></pre> <p><strong>EDIT:</strong> So it turns out that Python's equality on booleans is a little unexpected (at least to me):</p> <pre><code>&gt;&gt;&gt; True is 1 False &gt;&gt;&gt; True == 1 True &gt;&gt;&gt; True == 2 False &gt;&gt;&gt; False is 0 False &gt;&gt;&gt; False == 0 True &gt;&gt;&gt; False == 0.0 True </code></pre> <p>The rationale for this, as explained in <a href="http://docs.python.org/release/2.3.5/whatsnew/section-bool.html" rel="noreferrer">the notes when bools were introduced in Python 2.3.5</a>, is that the old behaviour of using integers 1 and 0 to represent True and False was good, but we just wanted more descriptive names for numbers we intended to represent truth values.</p> <p>One way to achieve that would have been to simply have <code>True = 1</code> and <code>False = 0</code> in the builtins; then 1 and True really would be indistinguishable (including by <code>is</code>). But that would also mean a function returning <code>True</code> would show <code>1</code> in the interactive interpreter, so what's been done instead is to create <code>bool</code> as a subtype of <code>int</code>. The only thing that's different about <code>bool</code> is <code>str</code> and <code>repr</code>; <code>bool</code> instances still have the same data as <code>int</code> instances, and still compare equality the same way, so <code>True == 1</code>.</p> <p>So it's wrong to use <code>x is True</code> when <code>x</code> might have been set by some code that expects that "True is just another way to spell 1", because there are lots of ways to construct values that are equal to <code>True</code> but do not have the same identity as it:</p> <pre><code>&gt;&gt;&gt; a = 1L &gt;&gt;&gt; b = 1L &gt;&gt;&gt; c = 1 &gt;&gt;&gt; d = 1.0 &gt;&gt;&gt; a == True, b == True, c == True, d == True (True, True, True, True) &gt;&gt;&gt; a is b, a is c, a is d, c is d (False, False, False, False) </code></pre> <p>And it's wrong to use <code>x == True</code> when <code>x</code> could be an arbitrary Python value and you only want to know whether it is the boolean value <code>True</code>. The only certainty we have is that just using <code>x</code> is best when you just want to test "truthiness". Thankfully that is usually all that is required, at least in the code I write!</p> <p>A more sure way would be <code>x == True and type(x) is bool</code>. But that's getting pretty verbose for a pretty obscure case. It also doesn't look very Pythonic by doing explicit type checking... but that really is what you're doing when you're trying to test precisely <code>True</code> rather than truthy; the duck typing way would be to accept truthy values and allow any user-defined class to declare itself to be truthy.</p> <p>If you're dealing with this extremely precise notion of truth where you not only don't consider non-empty collections to be true but also don't consider 1 to be true, then just using <code>x is True</code> is probably okay, because presumably then you know that <code>x</code> didn't come from code that considers 1 to be true. I don't think there's any pure-python way to come up with another <code>True</code> that lives at a different memory address (although you could probably do it from C), so this shouldn't ever break despite being theoretically the "wrong" thing to do.</p> <p>And I used to think booleans were simple!</p> <p><strong>End Edit</strong></p> <hr> <p>In the case of <code>None</code>, however, the idiom is to use <code>if x is None</code>. In many circumstances you can use <code>if not x</code>, because <code>None</code> is a "falsey" value to an <code>if</code> statement. But it's best to only do this if you're wanting to treat all falsey values (zero-valued numeric types, empty collections, and <code>None</code>) the same way. If you are dealing with a value that is either some possible other value or <code>None</code> to indicate "no value" (such as when a function returns <code>None</code> on failure), then it's <strong>much</strong> better to use <code>if x is None</code> so that you don't accidentally assume the function failed when it just happened to return an empty list, or the number 0.</p> <p>My arguments for using <code>==</code> rather than <code>is</code> for immutable value types would suggest that you should use <code>if x == None</code> rather than <code>if x is None</code>. However, in the case of <code>None</code> Python does explicitly guarantee that there is exactly one <code>None</code> in the entire universe, and normal idiomatic Python code uses <code>is</code>.</p> <hr> <p>Regarding whether to return <code>None</code> or raise an exception, it depends on the context.</p> <p>For something like your <code>get_attr</code> example I would expect it to raise an exception, because I'm going to be calling it like <code>do_something_with(get_attr(file))</code>. The normal expectation of the callers is that they'll get the attribute value, and having them get <code>None</code> and assume that was the attribute value is a much worse danger than forgetting to handle the exception when you can actually continue if the attribute can't be found. Plus, returning <code>None</code> to indicate failure means that <code>None</code> is not a valid value for the attribute. This can be a problem in some cases.</p> <p>For an imaginary function like <code>see_if_matching_file_exists</code>, that we provide a pattern to and it checks several places to see if there's a match, it could return a match if it finds one or <code>None</code> if it doesn't. But alternatively it could return a list of matches; then no match is just the empty list (which is also "falsey"; this is one of those situations where I'd just use <code>if x</code> to see if I got anything back).</p> <p>So when choosing between exceptions and <code>None</code> to indicate failure, you have to decide whether <code>None</code> is an expected non-failure value, and then look at the expectations of code calling the function. If the "normal" expectation is that there will be a valid value returned, and only occasionally will a caller be able to work fine whether or not a valid value is returned, then you should use exceptions to indicate failure. If it will be quite common for there to be no valid value, so callers will be expecting to handle both possibilities, then you can use <code>None</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload