Skip to content

Commit

Permalink
Only return a Deferred from DBObject.__new__ if afterInit actually re…
Browse files Browse the repository at this point in the history
…turns a Deferredl; refs bmuller#34

This does not ensure backwards compabitility--previously since
afterInit was not called during instantiation, instantiation was never
deferred--but sure does improve it by providing it in cases where
afterInit is not deferred.
  • Loading branch information
Erik Allik committed Nov 30, 2012
1 parent 344ff88 commit 4e80cc5
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
10 changes: 7 additions & 3 deletions twistar/dbobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,15 @@ class DBObject(Validator):
def __new__(cls, *args, **kwargs):
try:
ret = super(DBObject, cls).__new__(cls, *args, **kwargs)
ret.__init__(*args, **kwargs)
except:
return defer.fail()
else:
return defer.maybeDeferred(ret.afterInit).addCallback(lambda _: ret)
d = ret.afterInit()
if isinstance(d, defer.Deferred):
ret.__init__(*args, **kwargs)
return d.addCallback(lambda _: ret)
else:
return ret


def __init__(self, **kwargs):
Expand Down Expand Up @@ -387,7 +391,7 @@ def findOrCreate(klass, **attrs):
def _findOrCreate(trans):
def handle(result):
if len(result) == 0:
return klass(**attrs).addCallback(lambda inst: inst.save())
return defer.maybeDeferred(klass, **attrs).addCallback(lambda inst: inst.save())
return result[0]
return klass.findBy(**attrs).addCallback(handle)
return _findOrCreate()
Expand Down
2 changes: 1 addition & 1 deletion twistar/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def createInstances(props, klass):
"""
if type(props) is list:
return defer.DeferredList(
[klass(**prop) for prop in props], fireOnOneErrback=True, consumeErrors=True
[defer.maybeDeferred(klass, **prop) for prop in props], fireOnOneErrback=True, consumeErrors=True
).addCallback(lambda result: [x[1] for x in result])
elif props is not None:
return klass(**props)
Expand Down

0 comments on commit 4e80cc5

Please sign in to comment.