Groovy has a nice operator for safe dereferencing, which helps to avoid NullPointerExceptions:
variable?.method()
The method
will only be called, if variable
is not null
.
Is there a way to do the same in Python? Or do I have to write if variable: variable.method()
?
addressbook?.people?.'tim_yates'?.age
would return a value if none of the properties in the chain werenull
ornull
if one of them is – Waldonull
? Ignore it? Wouldn't you want to know why any of those values wasnull
, and log the problem? Or would you just show the user a message like "something went wrong somewhere, but we don't know what because we threw away the error", and then hope it doesn't happen again? – Anachronousif( addressbook != null && addressbook.people != null && addressbook.people.tim_yates != null...
etc... You still need to make the same decision, but it's a shorter, prettier journey to get there – Waldoaddressbook = GetAddressBookFromDatabase(db)
and the method throws an exception if it cannot connect / cannot find the addressbook / etc. Then you catch the exception and handle it! And ifaddressbook == null
when you try to use it, it's a bug in your code and it should cause an error, which you catch somewhere way up the callchain (since it should never happen, you don't have to catch it immediately). – Anachronousaddressbook
was just an example (maybe a badly thought out one), I was just trying to show where the null-safe operator is useful, not start a theological war – WaldoObject.try
method. It solves the same problem, but the ruby approach is more methody and less operatory. – Jett