Python Forum
Where is "switch" statement ? Do nobody needs it ? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: Where is "switch" statement ? Do nobody needs it ? (/thread-6359.html)

Pages: 1 2


Where is "switch" statement ? Do nobody needs it ? - vlad1777d - Nov-18-2017

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


RE: Where is "switch" statement ? Do nobody needs it ? - buran - Nov-18-2017

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



RE: Where is "switch" statement ? Do nobody needs it ? - metulburr - Nov-18-2017

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.


RE: Where is "switch" statement ? Do nobody needs it ? - wavic - Nov-18-2017

In Python the equivalent of switch statement is:

if condition:
    # do something
elif condition:
    # do something else
elif condition:
    # do another



RE: Where is "switch" statement ? Do nobody needs it ? - buran - Nov-18-2017

@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


RE: Where is "switch" statement ? Do nobody needs it ? - Larz60+ - Nov-19-2017

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()



RE: Where is "switch" statement ? Do nobody needs it ? - nilamo - Nov-19-2017

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.


RE: Where is "switch" statement ? Do nobody needs it ? - Kebap - Nov-20-2017

(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.


RE: Where is "switch" statement ? Do nobody needs it ? - buran - Nov-20-2017

(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 :-)


RE: Where is "switch" statement ? Do nobody needs it ? - vlad1777d - Nov-22-2017

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.