python How to call ob1.fun1.fun2 and handle ob1.fun1 as none?
<p>I tried to use the following code, but looks like ugly</p>

<pre><code>tmp = ob1.fun1
result = None
if tmp is not None:
   global result
   result = tmp.fun2
</code></pre>

<p>Is there a better way to do this?</p>

<p>Use the <a href="http://stackoverflow.com/questions/11360858/what-is-the-eafp-principle-in-python">EAFP</a> (Easier to ask for forgiveness than permission) approach. Wrap it in a try/except and handle your exception accordingly: </p>

<pre><code>result = None
try: 
    result = ob1.fun1.fun2
except AttributeError:
    # do your exception handling here
</code></pre>

<p>You could also use <a href="https://docs.python.org/3/library/functions.html#hasattr" rel="nofollow">hasattr</a> to check if <code>fun1</code> is in <code>ob1</code></p>

<pre><code>result = None
if hasattr(ob1, 'fun1'):
    res = ob1.fun1.fun2
else:
    print('no fun1 found in ob1')
    # or raise an Exception
</code></pre>

python