Saturday, February 19, 2022

WTF: Adding a dict to a list

 I found this strange way of adding a dict to a list in some production Python code:

result = [...]
dict_to_add = (
    "{\'ParameterKey\': \'"
    + param_key
    + "\', \'ParameterValue\': \'"
    + param_value
    + "\'}"
)
result.append(ast.literal_eval(dict_to_add))

As a start, those backslashes in the string are completely useless. My guess is that the guy used originally double quotes, which needed to be backslashed. Then he realized that it does not work, so he reverted to simple quotes, leaving the backslash characters.

But the big WTF is to use the ast library for transforming the string to a dict. Why would you do that in such a simple case? Why not simply build the dict directly:

result.append({'ParameterKey': param_key, 'ParameterValue': param_value})

That's a strange disease, I call it ast-ma.

No comments:

Post a Comment