2

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]

Community
  • 1
  • 1
Sergey Orshanskiy
  • 6,794
  • 1
  • 46
  • 50
  • Don't think there is anything better than your current method in Python. You could use `l = l and l.string` for the second line but this is significantly less readable and doesn't save much typing. – Andrew Clark Oct 24 '13 at 02:01

1 Answers1

4

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)
John La Rooy
  • 295,403
  • 53
  • 369
  • 502