Pergunta

Groovy has a very handy operator ?.. This checks if the object is not null and, if it is not, accesses a method or a property. Can I do the same thing in Python?

The closest I have found is the ternary conditional operator. Right now I am doing

l = u.find('loc')
l = l.string if l else None

whereas it would be nice to write

l = u.find('loc')?.string

Update: in addition to getattr mentioned below, I found a relatively nice way to do it with a list:

[x.string if x else None for x in [u.find('loc'), u.find('priority'), ...]]

Another alternative, if you want to exclude None:

[x.string for x in [u.find('loc'), u.find('priority'), ...] if x]

Foi útil?

Solução

You could write something like this

L = L and L.string

Important to note that as in your ternary example, this will do the "else" part for any "Falsy" value of L

If you need to check specifically for None, it's clearer to write

if L is not None:
    L = L.string

or for the any "Falsy" version

if L:
    L = L.string

I think using getattr is kind of awkward for this too

L = getattr(L, 'string', None)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top