What's the most idiomatic way to apply various transformations to a single variable in succession?
Here's an example. The following is a code snippet from my implementation of the cryptography algorithm AES:
subkeys = key_schedule(NUMBER_OF_ROUNDS)
matrix = binary_to_matrix(input_block)
matrix = add_round_key(matrix, subkeys[0])
for round in xrange(1, NUMBER_OF_ROUNDS):
matrix = sub_bytes(matrix)
matrix = shift_rows(matrix)
matrix = mix_columns(matrix)
matrix = add_round_key(matrix, subkeys[round])
matrix = sub_bytes(matrix)
matrix = shift_rows(matrix)
matrix = add_round_key(matrix, subkeys[-1])
Notice how the variable matrix get assigned to over and over again. How would you refactor this section of code to avoid this multi-assignment?
EDIT: One could perhaps approach the problem in this way:
for transformation in [sub_bytes, shift_rows, mix_columns, ...]:
matrix = transformation(matrix)
But this method doesn't help with functions that take multiple arguments like add_round_key (unless perhaps one used currying).
for line in fp: line = line.split(); line = [int(item) for item in line]matrixto something that expresses that it's a temporary value liketemp_calc_mat, and then assign a more descriptive name for when the calculations are done that represents the use of the final matrix (matrixis pretty much the worse name for that, we want to know what's the role of the matrix)Pipemodule as in stackoverflow.com/questions/12172934/method-chaining-in-python ?