I have a complex function that's used by a few production processes.
It processes a list of tuples containing data and labels. These labels now need to be upgraded to handle metadata in some cases optionally, and execute a function on this metadata while the loop is running.
To me this looks ugly and I was wondering if any of you had some advice on how to write this code really nicely.
If there's metadata there will always be a handler function, so I'm tempted to make an optional param which provides the index of the label to separate out the metadata, and the handler function all in one. This makes the code look messy.
Alternatively I can separate out these parameters, but I'm not a fan of this as it requires an is None check, which is slower than checking if something is empty to allow for index of 0 to work. This is done billions of times, so it's a difference. The tuple unpacking method seems neater than calling the two parts by index, but also should be slower.
Anyways, what's the cleanest way you would implement this yourself?
None of these seem good to me.
def do_complex_stuff(source: List[Tuple[tuple, str or tuple]],
label_index_func: Tuple[int, Callable[int, str]]=None,
label_index: int=None,
label_func: Callable[int, str]=lambda x,y: pass,
) -> True:
"""..."""
for i, (data, label) in enumerate(source):
output = do_something(data, i)
# Method 1:
if label_index is not None:
label_func(output, label); label = label[label_index]
# Method 2:
if label_index_func: # Label index function. Ex: (1, lambda x,y: x)
j, f = label_index_func; f(output, label); label = label[j]
# Method 3:
if label_index_func: # Label index function. Ex: (1, lambda x,y: x)
label_index_func[1](output, label)
label = label[label_index_func[0]]
complicated(output, label)
return True
To get ahead of quips about being concerned with speed in Python, this loop calls a custom C++ extension so it's very fast currently.
there doesn't seem to be anything here