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?
what about
def = variable.get('abc', {}).get('def',None)
well, this will only work for dict..
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With