3

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).

9
  • 2
    I wouldn't. I use that pattern to reinforce the idea that the data is constant, only the representation changes: for line in fp: line = line.split(); line = [int(item) for item in line] Commented Apr 5, 2016 at 22:26
  • I'd change the name of matrix to something that expresses that it's a temporary value like temp_calc_mat, and then assign a more descriptive name for when the calculations are done that represents the use of the final matrix (matrix is pretty much the worse name for that, we want to know what's the role of the matrix) Commented Apr 5, 2016 at 22:31
  • Maybe use the Pipe module as in stackoverflow.com/questions/12172934/method-chaining-in-python ? Commented Apr 5, 2016 at 22:31
  • in [..., lambda m: add_round_key(m, subkeys[round])] Commented Apr 5, 2016 at 22:32
  • 1
    If you find yourself doing this a lot, with variations in the functions you call, I think function composition could be an elegant solution. For just this single case, putting that exact code in a function seems simpler and easier to understand. Commented Apr 5, 2016 at 22:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.