Implementing switch/case statement in Python

Subscribe to my newsletter and never miss my upcoming articles

Do you know that Python doesn't have swich/case?

You might not even know that in Python, there is no switch/case statement like in Java or JavaScript and other programming languages. I was equally surprised when I found out that Python doesn't have switch/case statements, it's kind of crazy right? Well, that's how the language was built and I don't even know the reason why Python doesn't have switch/case statements.

In this small article, I will walk you through on how you can implement a switch/case statement in Python using a dictionary instead of relying on if-statement chaining that can get so annoying when too long. Not only can the if statement gets annoying but also not readable and difficult to maintain. If the code is not readable and difficult to maintain it's already a bad code right?

If your answer is yes then let's kick the ball rolling and learn this thing. But before that, I should make mention that this tutorial is not for a first day Python beginner as it will use some data structures that you will need to be familiar with. But all the same, you can still learn something, I will try to make it as easy as possible to understand.

Using if-else statement

Before we even being written the code for the switch statement like, let's first write the bad code using the if statement that is too nested.

def check_user(username):
    if lower(username) == "Mathews":
        print(f'Hello {username}!')
    elif username == "Joe":
        print(f'Hello {username}!')
    elif username == "John":
        print(f'Hello {username}!')
    elif username == 'Admin':
        print(f'Hello {username}!, You are super!')
    elif username == "Developer":
        print(f'Hello {username}! You are the creator!')
    ................
    ................
    else:
        print(f'Hello, "{username}" did not match any name.')

Of course, you can do something better than this like getting data from DB when the name matches. But for simplest, let's just print out the name a user enters.

check_user("Mathews")
#Out put
Hello Mathews!

check_user("Jaff")
#Out put
Hello, "Jeff" did not match any name.

When you look at this code, it will work just fine but the problem is that it's hard to read and maintain. I have added dots to show that the if statements are just way too long. If there can be a way of writing a readable code instead of this if-else statement it can be great. Yes, there is a way to get off this.

Using a dictionary

You can use dict as they are called or just a dictionary data structure that Python provides. Using a diction will help us write a better code that will achieve the same results. Here is the solution using dict data structure.

  def print_user(username):
  if username == 'Admin':
    print(f'Hello {username}! You are super!')
  elif username == "Developer":
      print(f'Hello {username}! You are the creator!')
  else: print(f'Hello {username}!')
def default(username):
  print(f'Hello, "{username}" did not match any.')
def check_user(username):
    return {
    "Mathews": print_user,
    "Joe": print_user,
    "John": print_user,
    "Developer": print_user,
    "Admin": print_user,
  }.get(username, default)(username)

Now let's test the code.

check_user("Mathews")
#Out put 
Hello Mathews!

#Enter a wrong name
check_user("Unkown")
#Out put 
Hello, "Unknown" did not match any name.

You have noted here, the function is passed in the diction as a value. This normal in Python because functions in Python are first-class citizens and can be passed in the data types like list, dictionaries, and so on.

Also instead of using users_dict[username] to pass a key in the dictionary, you can use get(key, default_value) so that you have control of the default value in the case where the key is invalid. This can help you with the KeyError when the key provided does not exist. You also noted that you can actually pass arguments to a function in a dictionary like this {'key':func}.get(username, default)(username)

Conclusion

If you have found using a dictionary instead of a long chain of if statements, why not introduce your team to this cleaner way of write code. If you have always wanted to use switch/case statements in Python, you can go ahead and try to implement this trick in your project using a dictionary. That is it for this post and I hope that you have learned something new.

No Comments Yet