5

What is the best technique with rethinkb and python to deal with empty result. I try this, but catching exceptions is not satisfactory.

@staticmethod
def get_by_mail(mail):
    try:
        return User(
            r.table('users').filter({"mail": mail}).limit(1).nth(0).run()
        )
    except RqlRuntimeError:
        return None

If anyone has tried other techniques, I am very interested. Thanks for your help.

5
  • It's not clear what do you want to do in case of rql runtime error. Commented Dec 4, 2013 at 14:13
  • 1
    I want to return None or an empty dict {} Commented Dec 4, 2013 at 14:19
  • Then what way your approach is not satisfactory? Commented Dec 4, 2013 at 14:20
  • I want to reduce the boilerplate Commented Dec 4, 2013 at 14:26
  • 1
    He search something like that github.com/rethinkdb/rethinkdb/issues/362#issuecomment-13749061 Commented Dec 4, 2013 at 14:50

2 Answers 2

3

The easiest way to deal with this is probably by adding in the element you want back with a union.

r.table('users').filter({"mail": mail}).limit(1).union([{}])[0]

A slightly ugly work around but it should do the trick. I think we should probably extend the default syntax to work with this. I'm going to make an issue for that.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I like this one liner.
1

That should work

r.table('users').filter({"mail": mail}).do( lambda users:
    r.branch(
        users.count() == 1,
        users.nth(0),
        None
     )
 )

You can also remove the nth(0) and retrieve a cursor and do:

user = None
for i in user:
     user = i
     break # You don't really need to break since there is at most one element

1 Comment

Thank you, I give it a try too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.