Search code examples
rethinkdbrethinkdb-python

how to unpack array into variables


Let's say we have this document:

doc = {'foo': 1, 'bar': 2, id: 123}

How can I do so that I can have, a pair with foo and bar values, the id and assign these to 2 variables? I need this so that I can use these variables inside my complicated query without having to copy / paste the same exact reql commands multiple times.

This is what I tried:

(
    r.expr(doc) # doc as input
    .do(lambda d: [
        # create the pair
        [d['id'], r.uuid(d['id'].coerce_to('string'))],
        # create the "values"
        d.without('id').values()
    ])
    .do(lambda x, y:  # unpacking should happen here
        # x should be the pair
        # y should be the values of foo and bar

        r.branch(
            # do something with x,
            # use y here,
            ...)
    )
    .map(lambda z:
        # use also x and y here
        # etc...
    .run(conn)
)

But I can't make this work. The idea is just to assign values to variables, to be used inside the query, for readability purposes. Some idea?


Solution

  • You can bind multiple variables in ReQL using r.do, for example:

    r.expr(doc).do(lambda d: # doc as input
      r.do(
        [d['id'], r.uuid(d['id'].coerce_to('string'))],
        d.without('id').values(),
        lambda x, y:
          # x is the pair
          # y is the values of bar and foo
          ...))