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.

Monday, February 7, 2022

WTF: Hair Splitting

 You know how sometimes, you find a very bad code, but it manages to teach you something? I just had this funny experience in a production code in python.

It happens that you have a full path to a file and you just need the filename. You do not need to be cross platform, or care for corner cases, so you just use the split method:

filename = filename.split('/')[-1]

You split around the slash characters, and you keep just the last part. Now I found this approach in production code:

boolean_slash_in_str = True
while boolean_slash_in_str:
    filename = filename.split('/', 1)[-1]
    if '/' not in filename:
        boolean_slash_in_str = False

It uses an ugly named and useless boolean value for the loop, but it also uses split with a second parameter I did not know about. So thanks to this code, I now know that you can specify the max number of splits. Here, it splits only around the first slash, keep the last part, and repeats until all slash characters are out.

Thanks for the lesson...