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 ?
#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


Messages In This Thread
RE: Where is "switch" statement ? Do nobody needs it ? - by vlad1777d - Nov-22-2017, 10:30 PM

Forum Jump:

User Panel Messages

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