Python Forum
Where is "switch" statement ? Do nobody needs it ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Where is "switch" statement ? Do nobody needs it ?
#1
Hello.

I wonder that in Python there's absent "switch" statement.
And the most interesting - nobody asks about it, nobody discusses it.
Seems, it's very often used in Javascript/Coffeescript, who have such statement.
But in Python it's absent.
There were added some less often-used features in Python, like decorators, "with" statements, "as" operator.
But no "switch" Cry .

Please, tell me what do you think about this.
Maybe I don't know something and writing each time "if somevar == 'SOMEVALUE'" is a better practice ? Smile

Thank you.
Best regards,
Vladislav
Reply
#2
In python we use dict for this , e.g something like this basic example:

 
def foo():
    print('This is call from foo.')

def bar():
    print('This is call from bar.')

my_switch = {'1':foo, '2':bar}
while True:
    user_input = input('Select function to execute (1 for foo, 2 for bar): ' )
    try:
        my_switch[user_input]()
    except KeyError:
        print('This is not valid input')
        break
Output:
Select function to execute (1 for foo, 2 for bar): 2 This is call from bar. Select function to execute (1 for foo, 2 for bar): 1 This is call from foo. Select function to execute (1 for foo, 2 for bar): 1 This is call from foo. Select function to execute (1 for foo, 2 for bar): 2 This is call from bar. Select function to execute (1 for foo, 2 for bar): 3 This is not valid input
Reply
#3
I always actually thought when doing c++ that switch was repetitive. I always just used the if condition there. But when i came to python, i loved the dictionary method. I never looked back.
Recommended Tutorials:
Reply
#4
In Python the equivalent of switch statement is:

if condition:
    # do something
elif condition:
    # do something else
elif condition:
    # do another
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
@wavic there is if/else also in javascript and virtually in any language and that is what OP doesn't want to do/ does not ask about it
Reply
#6
try this:
class PseudoSwitch:
    def __init__(self):
        self.exec_dict = {
            '1': self.function1,
            '2': self.function2,
            '3': self.function3
        }

    def function1(self):
        print('You ran function 1')

    def function2(self):
        print('You ran function 2')

    def function3(self):
        print('You ran function 3')

    def tryit(self):
        try:
            choice = input('enter function number: ')
            print(choice)
            self.exec_dict[choice]()
        except:
            'function out of range, use 1 2 or 3'

def main():
    ps = PseudoSwitch()
    ps.tryit()


if __name__ == '__main__':
    main()
Reply
#7
Switch is just a pattern matching construct.  Javascript/coffeescript have a pretty mediocre version of it, so in my opinion, Python lacking it at all is better than having a halfway useful feature.

Now, if it could match on ranges, conditional checks, the type of the param (is_instance), or the return value of a function, instead of just whatever specific value it has, then it'd be more useful.  But as is, it is rarely useful even in javascript.
Reply
#8
(Nov-18-2017, 01:35 PM)buran Wrote:
my_switch = {'1':foo, '2':bar}
while True:
    user_input = input('Select function to execute (1 for foo, 2 for bar): ' )

I would even go as far to have the options be calculated from the dictionary, so if you change the dict, the question will automatically mention the new function as an option as well, and you don't have to think about changing two places.
Reply
#9
(Nov-20-2017, 11:57 AM)Kebap Wrote: I would even go as far to have the options be calculated from the dictionary, so if you change the dict, the question will automatically mention the new function as an option as well, and you don't have to think about changing two places.
I agree for production/real-life code, but this was meant as merely an example :-)
Reply
#10
Thank you very much for this. It's as for me, very good idea =)

(Nov-19-2017, 03:05 AM)Larz60+ Wrote: try this:
class PseudoSwitch:
    def __init__(self):
        self.exec_dict = {
            '1': self.function1,
            '2': self.function2,
            '3': self.function3
        }

    def function1(self):
        print('You ran function 1')

    def function2(self):
        print('You ran function 2')

    def function3(self):
        print('You ran function 3')

    def tryit(self):
        try:
            choice = input('enter function number: ')
            print(choice)
            self.exec_dict[choice]()
        except:
            'function out of range, use 1 2 or 3'

def main():
    ps = PseudoSwitch()
    ps.tryit()


if __name__ == '__main__':
    main()

Thanks, it's a good idea =)

(Nov-19-2017, 04:48 PM)nilamo Wrote: Switch is just a pattern matching construct.  Javascript/coffeescript have a pretty mediocre version of it, so in my opinion, Python lacking it at all is better than having a halfway useful feature.

Now, if it could match on ranges, conditional checks, the type of the param (is_instance), or the return value of a function, instead of just whatever specific value it has, then it'd be more useful.  But as is, it is rarely useful even in javascript.

I don't know, I really often use it. Maybe as often, as if-else construction...

I wonder, why do lesser often used syntax features were added (decorators, with, as) to language; though they could be expressed as you just expressed "switch" statement - through current language features.

Decorators - through functions, as - through "=", with - through classes or functions.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020