Switch Case Statements in Python

Switch case statements are very popular conditional control statements in almost all programming languages. But surprisingly this is not available in python.

Question: Is there any switch case statements in python ?

Answer: The direct answer is NO

Alternative options for switch case statements in python

Option 1: Using If – elif – else statements. An example is given below.

if case == "case1":
    execute_func_case1()
elif case == "case2":
    execute_func_case2()
elif case == "case3":
    execute_func_case3()
else:
    execute_default_func()

Wow. Excellent.  The above code looks good right ?. It works exactly like switch-case statements, then why need switch-case statements in Python ?

Have you noticed a problem ?. The above if-elif-else conditions are fine as long as we have less number of cases. Imagine the situation with 10 or more elif conditions. Now you got the problem right ?.

Lets try the second option

Option 2: Using List in Python as an alternative to switch case statements

An example is given below.

def add(a, b):
    return a + b

def sub(a, b):
    return a-b

case_funcs = [add, sub]

case_funcs[0](1, 2)
case_funcs[1](1, 2)

 

In the above program, we don’t have to use if-elif-else blocks, instead, we can call using the position or index of the list and call the function. This looks better than the previous option right ?. But what about the default case ?. Also what if someone types an option greater than the size of the list ?. It will throw exception and there is no way to handle default case.

Option 3: Using Dictionary as alternative to switch case statements in python

An example is given below.

def add(a, b):
    return a + b

def sub(a, b):
    return a-b

case_funcs = {'sum':add, 'subtract':sub}

case_funcs['sum'](1,2)

 

Here the implementation is much similar to the switch case statement. We use a key to identify or route to the required case or function. The keys can be anything and are not limited by the indices or positions.

Now lets talk about the drawbacks of the above implementation. The above method will throw KeyError if we pass an unknown key. Also there is no default case statement. How will we handle these problems?

Check the below program

def add(a, b):
    return a + b

def sub(a, b):
    return a-b

def default(a, b):
    return "Default Return"

case_funcs = {'sum':add, 'subtract':sub}

# sum is the key for the add(). 
# default is the default function that gets called for non existent keys
# (1, 2) are the arguments for the function
print(case_funcs.get('sum',default)(1,2))

 

Python dictionary has a get() method that returns the value based on the key. This has one more feature. We can configure a default value for non-existent keys. Wow now we got the solution.

So by using this feature, we can implement the switch-case like feature in python.

Route internet traffic through a specific interface in Linux Servers – CentOS / RHEL

I have a server with multiple network interfaces. Out of that two of them were connected to two different networks. My requirement is to route the internet traffic through the second interface. The Server is running with CentOS 7 operating system. The second interface is connected to a network with higher internet bandwidth and the first interface is connected to a network with lower bandwidth. So I have to make the second interface as the primary/default interface.

The details of the network interfaces are given below.

Details of first interface:

Interface name -> eno2

IP Address:  192.168.0.208

Gateway 192.168.0.1

Internet Provider : ISP01

Details of second interface:

Interface name -> eno3

IP Address:  172.31.0.208

Gateway 172.31.0.1

Internet Provider : ISP02

The diagrammatic view of the server and network connections are given below.

internet_routing

Problem statement:

The internet traffic is going through the first interface. I want to change it to the second interface.

How to check the route of the internet traffic ?

This can be checked by using the traceroute command. Execute the following commands and check hops. If it is going through the gateway of the first network, means traffic is routed through the first interface. If it is going through the gateway of the second network, means that the traffic is routed through the second interface.

traceroute google.com

When I executed this command, I got the following output that proves that the traffic was going through the first interface. 192.168.0.1 is the gateway of the first interface. You can see the details in the below screenshot.

traceroute_02

How to list the default traffic routes ?

To list the existing routes in the system, type the following command in the terminal.

ip route list

This will list all the routes and that shows the default routes also. The following screenshot shows the details of the routes in my system.

iproute_list01

In the above image, you can see two default routes. The first one has a priority of 102 and second one with priority 103. So based on the priority, the traffic goes through the first interface (gateway 192.168.0.1, ISP-01).

How to change the default / primary route ?

In my case there were two default routes. So making one interface as the default or primary route will solve the problem.

This can be enabled by configuring the DEFROUTE parameter in the network interface settings. The network interface configurations are present in the following directory.

/etc/sysconfig/network-scripts

In this directory, you can see files that starts with ifcfg-. In my case, the two files that I have to deal with are ifcfg-eno2 and ifcfg-eno3.

In this file, there will be a parameter DEFROUTE. If it is configured with value “yes” means that interface is a default route. If the value is “no” means it is not a default interface.

So make DEFROUTE=no in the first interface (ifcfg-eno2) and DEFROUTE=yes in the second interface (ifcfg-eno3).

Restart the network after making these changes. The command is shared below.

service network restart

Now check the route list and see the default route/s. The command is given below.

ip route list

The screenshot from my system is shared below.

iproute_list02

Now you can see that the second interface (gateway 172.31.0.1 & ISP-02) became the default interface and the first interface got removed from the default list. It is present in the available interfaces, but not the default interface.

Now let us test the internet traffic through traceroute command. As per our configuration, the traffic should go through the second interface. The command is given below.

traceroute google.com

The screenshot from my system is given below.

traceroute_01

As per the screenshot, the traffic is going as expected based on our configuration. It is going through the second interface.

The steps for Ubuntu and other operating systems are also similar. Here I have explained based on CentOS & RHEL operating systems.

Hope this article helps someone. 🙂