5 Common Anti-Patterns in Python

Making analysis results more useful and relevant is one of our primary goals at DeepSource, and we are regularly adding more capabilities to our core analyzers.

1. Not using with to open files

When you open a file without the with statement, you need to remember closing the file via calling close() explicitly when finished with processing it. Even while explicitly closing the resource, there are chances of exceptions before the resource is actually released. This can cause inconsistencies, or leading the file to be corrupted. Opening a file via with implements the context manager protocol that release the resource when execution is outside of the with block.

2. Using list/dict/set comprehension unnecessarily

Built-in functions like all, any, enumerate, iter, itertools.cycle, itertools.accumulate, can work directly with a generator expression. They do not require comprehension.

In addition to them: all() and any() in Python also support short-circuiting, but this behavior is lost if comprehension is used. This affects performance.

3. Unnecessary use of generators

It is unnecessary to use a generator expression within a call to list, dict or set since there are comprehensions for each of these types. Instead of using list/dict/set around a generator expression, they can be written as their respective comprehension.

This anti-pattern affects the readability of code. Often we see code to create a variable, assign a default value to it, and then checking the dictionary for a certain key. If the key exists, then the value of the key is assigned into the value for the variable. Although there is nothing wrong in doing this, it is verbose and inefficient as it queries the dictionary twice, while it can be easily done using the get() method for the dictionary.

This anti-pattern affects the readability of code. Often we see code to create a variable, assign a default value to it, and then checking the dictionary for a certain key. If the key exists, then the value of the key is assigned into the value for the variable. Although there is nothing wrong in doing this, it is verbose and inefficient as it queries the dictionary twice, while it can be easily done using the get() method for the dictionary.

This anti-pattern affects the readability of code. Often we see code to create a variable, assign a default value to it, and then checking the dictionary for a certain key. If the key exists, then the value of the key is assigned into the value for the variable. Although there is nothing wrong in doing this, it is verbose and inefficient as it queries the dictionary twice, while it can be easily done using the get() method for the dictionary.

Contents

Our latest articles

Let’s keep in touch!

Subscribe to newsletter and get our latest articles, events and news!