Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safely access objects in Python without try / catch

In Objective-C you can do [variable valueForKeyPath:@"abc.def"] or [[variable abc] def] and if abc doesn't exist on variable you'll get a nil value in the end and will not get an error or exception. This is really convenient. Is there something like this in Python? I know you can do (for dictionaries at least)

abc = variable.get('abc', None)
if abc:
    def = abc.get('def', None)

or

try:
    def = variable.get('abc').get('def')
except:
    pass

which seems incredibly verbose. Is there an easier way when I just want to access an object's attribute or get a None value back?

like image 770
Tony Avatar asked Sep 29 '26 00:09

Tony


2 Answers

what about

def = variable.get('abc', {}).get('def',None)

well, this will only work for dict..

like image 160
Marcus Avatar answered Oct 01 '26 15:10

Marcus


You can use nested calls to getattr:

def = getattr( getattr(variable, 'abc', None), 'def', None)

You can also dispense with the methods, and just catch the AttributeError

try:
    def = variable.abc.def
except AttributeError:
    def = None
like image 38
chepner Avatar answered Oct 01 '26 13:10

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!