Chained Conditions that require order to not produce order
<p>Whenever I <strong>chain conditions</strong> in Python (or any other language tbh) I stumble upon asking myself this, kicking me out of the productive "Zone". 
When I chain conditions I can, by ordering them correctly, check conditions that without checking for the other conditions first, may produce an Error.</p>

<p>As an example lets assume the following snippet:</p>

<pre class="lang-py prettyprint-override"><code>if "attr" in some_dictionary and some_value in some_dictionary["attr"]:
    print("whooohooo")
</code></pre>

<p>If the first condition wasnt in the first place or even absent, the second condition my produce an <code>KeyError</code></p>

<p>I do this pretty often to simply save space in the code, but I always wondered, if this is good style, if it comes with a risk or if its simply "pythonic".</p>

<p>Python is a late binding language, which is reflected in these kind of checks. The behavior is called <a href="https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not" rel="nofollow">short-circuiting</a>. One thing I often do is:</p>

<pre><code>def do(condition_check=None):
    if condition_check is not None and condition_check():
        # do stuff
</code></pre>

<p>Now, many people will argue that <code>try: except:</code> is more appropriate. This really depends on the use case!</p>

<ul>
<li><code>if</code> expressions are faster when the check is likely to fail, so use them when you know what is happening.</li>
<li><code>try</code> expressions are faster when the check is likely to succeed, so use them to safeguard against exceptional circumstances.</li>
<li><code>if</code> is explicit, so you know precisely what you are checking. Use it if you know what is happening, i.e. strongly typed situations.</li>
<li><code>try</code> is implicit, so you only have to care about the outcome of a call. Use it when you don't care about the details, i.e. in weakly typed situations.</li>
<li><code>if</code> works in a well-defined scope - namely right where you are performing the check. Use it for nested relations, where you want to check the top-most one.</li>
<li><code>try</code> works on the entire contained call stack - an exception may be thrown several function calls deeper. Use it for flat or well-defined calls.</li>
</ul>

<p>Basically, <code>if</code> is a precision tool, while <code>try</code> is a hammer - sometimes you need precision, and sometimes you just have nails.</p>

python condition keyerror