top of page
  • Writer's pictureRan Isenberg

Reduce Python Code Complexity With This Simple Trick

Updated: Feb 18, 2023

pexels free images

As engineers, we should always strive to write simple code.

One common pitfall which is typical to many programming languages and not only to Python is the horrible if-elif misusage.

If you want to tackle this issue and to improve your code readability and maintainability, stick around, this article is for you!


Request Handler Use Case

A customer management system receives requests.

Request action type
Request action type

Each request contains an action and a customer name. Actions consist of creating a new customer, activating a customer, suspending a customer, and deleting a customer.

There are four types, and each type is handled differently.

Each request is a Python dictionary:


Here is a potential flow diagram that tackles this use case:

And the equivalent Python code:

Can you spot the issue? There are many if and elifs

that make the code more complex, less readable (too long!), and harder to maintain.

In addition, in order to handle the actions, the code sometimes has to go through several ‘ifs’ that won’t match, which is not ideal as the number of actions gets bigger (complexity of O(n) where n is the number of actions).

Thankfully, there is a straightforward solution!

Say no to If-elif!

As you can see in the code below, the if-elif section is removed in favor of a dictionary that maps each action to the corresponding handler function — line 3, ACTION_MAPPING.

Now, any action handler is selected immediately at line 18 from the dictionary (at average order of O(1)), and the handler is called at line 20.

For example, for an ‘activate’ action, the _handle_activate_request will be selected.

Side note: since the input is validated at line 13, the action is always found in the ACTION_MAPPING dictionary.


What is the Best Practice?

If-elif isn’t evil; they are an essential part of the language.

However, like with everything else in life, you shouldn’t overdo it.

My rule of thumb is that one if-elif is enough. If you require more, use the dictionary mapping mechanism.

And lastly, use a code complexity scanner tool such as Radon/Xenon. They can pinpoint problematic areas and help you refactor your code into a masterpiece.


bottom of page