More pythonic way to write this?

I have this code here:

import re
def get_attr(str, attr):
    m = re.search(attr + r'=(\w+)', str)
    return None if not m else m.group(1)

str = 'type=greeting hello=world'

print get_attr(str, 'type')   # greeting    
print get_attr(str, 'hello')  # world
print get_attr(str, 'attr')   # None

Which works, but I don't particularly like this line:

return None if not m else m.group(1)

In my opinion, this would look cleaner if we could use the ternary operator:

return (m ? m.group(1) : None)

But this, of course, is not. What are you offering?

+5
source share
4 answers

Python has a ternary operator. You use it. It is just in shape X if Y else Z.

However, I tend to write these things. Attaching things on one line is not so great if you sacrifice clarity.

def get_attr(str, attr):
    m = re.search(attr + r'=(\w+)', str)
    if m:
        return m.group(1)

    return None
+10
source

Another option is to use:

return m.group(1) if m else m

It is explicit, and you do not need to do logic puzzles to figure it out :)

+4
source
return m and m.group(1)

Pythonic .

m None ( - , "" ), m, m "true-ish", m.group(1).

+3
source

You have a python conditional statement. IMO this is completely pythonic as-is and needs no change. Remember explicit is better than implicit. Now you have readability and instantly understandable.

+2
source

All Articles