Reputation: 85458
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?
Upvotes: 5
Views: 1058
Reputation: 879093
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 :)
Upvotes: 4
Reputation: 37431
What you have there is python's conditional operator. IMO it's perfectly pythonic as-is and needs no change. Remember, explicit is better than implicit
. What you have now is readable and instantly understandable.
Upvotes: 2
Reputation: 90161
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
Upvotes: 10
Reputation: 258128
return m and m.group(1)
would be one Pythonic way to do it.
If m
is None
(or something else that evaluates "falsely"), it returns m
, but if m
is "true-ish", then it returns m.group(1)
.
Upvotes: 3