elegant unpacking variable-length tuples

2024/9/23 17:54:03

A real, if silly problem:

https://github.com/joshmarshall/tornadorpc/blob/master/tornadorpc/base.py

def start_server(handlers, ...):...for (route, handler) in handlers:...

Normally "handlers" is a list of 2-element tuples. But with this particular solution (Tornado) you can pass a third argument to a particular handler (kw args). So a tuple in "handlers" may have 2 elems sometimes or 3 elems other times.

I need to unpack this in a loop. Sure, I can do smth like length checking or try..except on unpacking. Ugh.

Can you think of smth better/more clever than this:

In [8]: handlers
Out[8]: [(1, 2), (3, 4, 5), (6, 7)]In [9]: new_handlers = [x + (None,) for x in handlers]

?

Answer

If that handler takes keyword arguments, then use a dictionary for the third element:

handlers = [(1, 2, {}), (3, 4, {'keyword': 5), (6, 7, {})]for route, handler, kwargs in handlers:some_method(route, handler, **kwargs)

Or you can apply the arguments using *args syntax; in that case just catch all values in the loop:

for args in handlers:some_method(*args)

If you have to unpack into at least 2 arguments, do so in a separate step:

for handler in handlers:route, handler, args = (handler[0], handler[1], handler[2:])

where args would be a tuple of 0 or more elements.

In Python 3, you can handle arbitrary width unpacking with a splat (*) target:

for route, handlers, *args in handlers:

where *args captures 0 or more extra values in the unpack.

The other route, to elements in handlers to a minimal length could be done with:

[(h + (None,) * 3)[:3] for h in handlers]

Demo:

>>> handlers = [(1, 2), (3, 4, 5), (6, 7)]
>>> [(h + (None,) * 3)[:3] for h in handlers]
[(1, 2, None), (3, 4, 5), (6, 7, None)]
https://en.xdnf.cn/q/71759.html

Related Q&A

Extracting data from a 3D scatter plot in matplotlib

Im writing an interface for making 3D scatter plots in matplotlib, and Id like to access the data from a python script. For a 2D scatter plot, I know the process would be:import numpy as np from matpl…

How does Pythonic garbage collection with numpy array appends and deletes?

I am trying to adapt the underlying structure of plotting code (matplotlib) that is updated on a timer to go from using Python lists for the plot data to using numpy arrays. I want to be able to lower …

What is the default if I install virtualenv using pip and pip3 respectively?

I used sudo pip install virtualenv, then when I run virtualenv ENV in a directory, I get a Python 2 virtual enviroment.If I use pip3 install virtualenv to install virtualenv again, will it override the…

Flask Admin ModelView different fields between CREATE and EDIT

In a Flask app using Flask Admin I would like to be able to define different form fields in the Edit section of a ModelView than those in the Create section.The form_columns setting applies to both Cre…

Python compilation error: LONG_BIT definition appears wrong for platform

This error message is not unknown, I have already reinstalled many packages, but so far not yet found a solution.I get the following error from the command pip install cryptography/usr/include/python2.…

Randomly sampling lines from a file

I have a csv file which is ~40gb and 1800000 lines. I want to randomly sample 10,000 lines and print them to a new file.Right now, my approach is to use sed as:(sed -n $vars < input.txt) > output…

Is Pythons hashlib.sha256(x).hexdigest() equivalent to Rs digest(x,algo=sha256)

Im not a python programmer, but Im trying to translate some Python code to R. The piece of python code Im having trouble with is:hashlib.sha256(x).hexdigest()My interpretation of this code is that the…

How to do Histogram Equalization on specific area

I have a image and I want to do HE or CLAHE on specific area of the image. I already have a mask for the image. Is there any possible way to do so?

Timing out a multiprocessing function

I need to set a time limit on a python function which use some multiprocessing stuff (I dont know if it matters). Something like this:function(a_list):p1 = Process(a_list[0:len(a_list/2)])p2 = Process(…

How can I get the actual axis limits when using ax.axis(equal)?

I am using ax.axes(equal) to make the axis spacing equal on X and Y, and also setting xlim and ylim. This over-constrains the problem and the actual limits are not what I set in ax.set_xlim() or ax.set…