Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More pythonic way to write this?

Tags:

python

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 am not particularly fond of this line:

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

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

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

But that of course isn't there. What do you suggest?

like image 365
NullUserException Avatar asked Sep 29 '10 16:09

NullUserException


2 Answers

Python has a ternary operator. You're using it. It's just in the X if Y else Z form.

That said, I'm prone to writing these things out. Fitting things on one line isn't 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
like image 147
Chris B. Avatar answered Sep 19 '22 18:09

Chris B.


Another option is to use:

return m.group(1) if m else m

It's explicit, and you don't have to do any logic puzzles to understand it :)

like image 39
unutbu Avatar answered Sep 20 '22 18:09

unutbu