Safe dereferencing in Python

14,494

Solution 1

First of all, your options depend on what you'd like the expression to evaluate to if the variable is not dereferencable. I'll assume None is the appropriate result in these examples.

A common idiom for some circumstances in Python uses conditional expressions:

variable.method() if variable is not None else None

While this need may not be widespread, there are circumstances where it would be useful, especially when the references are nested and you would want something like this, where that idiom quickly gets cumbersome.

a?.b?.c?.d

Note that support for a ?. operator for safe deferencing is one of the main topics of PEP 505: None-aware operators \| Python.org. It's current status is "deferred".

Some discussion of it is at:

Solution 2

I've used this feature in Groovy, so I won't repeat the blub paradox of other posters.

In Groovy a statement like this

if(possiblyNull?.value){
    ...

Does this in Python

try:
    testVar = possiblyNull.value
except:
    testVar = None
if(testVar): 

It's definitely a cool feature in Groovy, and is helpful in removing syntactical noise. There are a few other bits of syntactical sugar, like the Elvis operator or *, but they do sacrifice legibility as the expense for quick fix symbols (in other words, they're no Pythonic).

Hope that helps :-)

Solution 3

An idiom I have seen and used is callable(func) and func(a, b, c) in place of a plain function call (where the return value is not used). If you are trying to use the return value, however, this idiom will yield False if the function is not callable, which may not be what you want. In this case you can use the ternary operator to supply a default value. For example, if the function would return a list that you would iterate over, you could use an empty list as a default value with func(a, b, c) if callable(func) else [].

Share:
14,494
deamon
Author by

deamon

Updated on June 19, 2022

Comments

  • deamon
    deamon almost 2 years

    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()?