Reputation: 28064
Using python 2.7, I have the following code:
if result != None:
(data,) = result
return data
return None
The result
variable is returned from a sqlite3 query that returns only one value. If the query returns a result, I want to unpack and return the data, otherwise I want to return None. The code above seems overly verbose and not at all pythonic. Is there a better way?
Upvotes: 3
Views: 9389
Reputation: 20339
Apart from the ;
that you left and the fact that result != None
should be replaced by result is not None
, I have no issues with your code.
It's simple, quite understandable, and won't silently fail you if one of these days your request returns 2 elements or more: it will raise an exception instead of silently returning the first element, like all the solutions so far.
Upvotes: 0
Reputation: 1123420
You could use a if
else
condition:
return result[0] if result is not None else None
or simplify this down to:
return result[0] if result else None
if you don't care about result
possibly being some other false-y value such as an empty tuple and such.
Upvotes: 10
Reputation: 310049
I suppose no answer is complete without try/except
:
try:
return result[0]
except TypeError,IndexError:
return None
Upvotes: 1
Reputation: 977
A way could be:
if result is not None:
return result[0]
return None
There is also a more compact way to do this:
return (result or [None])[0]
but the first is more clear.
Please avoid using semicolon at the end (is not C code), and reading python documentation helps you. It's a well-spent time.
Upvotes: 2
Reputation: 134631
Assuming that you'll only get either non-empty tuple or None, the simplest way:
return result and result[0]
Upvotes: 4