python - elegant unpacking variable-length tuples -
a real, if silly problem:
https://github.com/joshmarshall/tornadorpc/blob/master/tornadorpc/base.py
def start_server(handlers, ...): ... (route, handler) in handlers: ...
normally "handlers" list of 2-element tuples. particular solution (tornado) can pass third argument particular handler (kw args). tuple in "handlers" may have 2 elems or 3 elems other times.
i need unpack in loop. sure, can smth length checking or try..except on unpacking. ugh.
can think of smth better/more clever this:
in [8]: handlers out[8]: [(1, 2), (3, 4, 5), (6, 7)] in [9]: new_handlers = [x + (none,) x in handlers]
?
if handler takes keyword arguments, use dictionary third element:
handlers = [(1, 2, {}), (3, 4, {'keyword': 5), (6, 7, {})] route, handler, kwargs in handlers: some_method(route, handler, **kwargs)
or can apply arguments using *args
syntax; in case catch all values in loop:
for args in handlers: some_method(*args)
if have unpack @ least 2 arguments, in separate step:
for handler in handlers: route, handler, args = (handler[0], handler[1], handler[2:])
where args
tuple of 0 or more elements.
in python 3, can handle arbitrary width unpacking splat (*
) target:
for route, handlers, *args in handlers:
where *args
captures 0 or more extra values in unpack.
the other route, elements in handlers
minimal length done with:
[(h + (none,) * 3)[:3] h in handlers]
demo:
>>> handlers = [(1, 2), (3, 4, 5), (6, 7)] >>> [(h + (none,) * 3)[:3] h in handlers] [(1, 2, none), (3, 4, 5), (6, 7, none)]
Comments
Post a Comment