0

I tried to use the following code, but looks like ugly

tmp = ob1.fun1
result = None
if tmp is not None:
   global result
   result = tmp.fun2

Is there a better way to do this?

Daniel Wu
  • 5,853
  • 12
  • 42
  • 93

3 Answers3

1

If you just want result to be None if ob1.fun1 is None or if fun2 doesn't exist as an attribute, you could use getattr and use None as a default. Note that getattr(None, 'attr', something) will return something.

result = getattr(ob1.fun1, 'fun2', None)
Karin
  • 8,404
  • 25
  • 34
0

Use the EAFP (Easier to ask for forgiveness than permission) approach. Wrap it in a try/except and handle your exception accordingly:

result = None
try: 
    result = ob1.fun1.fun2
except AttributeError:
    # do your exception handling here

You could also use hasattr to check if fun1 is in ob1

result = None
if hasattr(ob1, 'fun1'):
    res = ob1.fun1.fun2
else:
    print('no fun1 found in ob1')
    # or raise an Exception
Community
  • 1
  • 1
idjaw
  • 25,487
  • 7
  • 64
  • 83
0

How about:

if t.fun1 is not None:
  result = t.fun1.fun2
else:
  result = None
user2436850
  • 178
  • 6