Skip to content

Commit f4a7bf3

Browse files
committed
Add support for one(..., default=Exception)
I have discovered on Gittip that I want this feature (to replace the assert_one_payday function)
1 parent fe83969 commit f4a7bf3

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

postgres/__init__.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,7 @@
166166
except ImportError: # Python 3
167167
import urllib.parse as urlparse
168168
from collections import namedtuple
169+
from inspect import isclass
169170

170171
import psycopg2
171172
from postgres.orm import Model
@@ -409,7 +410,15 @@ def one(self, sql, parameters=None, back_as=None, default=None, *a, **kw):
409410
>>> db.one("SELECT * FROM foo WHERE bar='blam'", default=False)
410411
False
411412
412-
We specifically don't support passing lambdas or other callables for
413+
If you pass an :py:class:`Exception` instance or subclass, we will
414+
raise that for you:
415+
416+
>>> db.one("SELECT * FROM foo WHERE bar='blam'", default=Exception)
417+
Traceback (most recent call last):
418+
...
419+
Exception
420+
421+
We specifically stop short of supporting lambdas or other callables for
413422
the :py:attr:`default` parameter. That gets complicated quickly, and
414423
it's easy to just check the return value in the caller and do your
415424
extra logic there.
@@ -471,6 +480,8 @@ def one(self, sql, parameters=None, back_as=None, default=None, *a, **kw):
471480

472481
# default
473482
if out is None:
483+
if isexception(default):
484+
raise default
474485
out = default
475486

476487
return out
@@ -900,6 +911,17 @@ def make(self, values):
900911
return DelegatingCaster
901912

902913

914+
def isexception(obj):
915+
"""Given an object, return a boolean indicating whether it is an instance
916+
or subclass of Exception.
917+
"""
918+
if isinstance(obj, Exception):
919+
return True
920+
if isclass(obj) and issubclass(obj, Exception):
921+
return True
922+
return False
923+
924+
903925
if __name__ == '__main__':
904926
db = Postgres("postgres://jrandom@localhost/test")
905927
db.run("DROP SCHEMA IF EXISTS public CASCADE")

0 commit comments

Comments
 (0)