Skip to content

The Python programming language with switch case!

License

Notifications You must be signed in to change notification settings

cmrfrd/cpython-switchcase

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

python switch case

This is Python version 3.9.0 alpha 0 with Switch Case!!

By: Alex Comerford ([email protected])

To read the original readme for cpython, build instructions, and more go to README.rst

What is this fork?

This fork of cpython adds two new statements to the python core language, switch and case. Requisite changes have been made to the python grammar, asdl, and AST compiler to support execution of these statements.

The new syntax for these statements is

switch EXPR:
    case EXPR:
        SUITE
    case EXPR:
        SUITE
    else:
        SUITE

Sample code

var = 1
switch var:
    case 0:
        print("it's zero!")
    case 1:
        print("it's one!")
    else:
        print("it's something else!")

evaluates to

it's one!

Why do this?

There have been previous PEP's proposing switching on multiple values here and here which have been subsequently denied in favor of using if/elif chains. However switch case can be extremely handy in some situations in which if/elif chains might feel a little verbose.

Example:

switch input(">"):           x = input(">")
    case 'hello':            if x == 'hello':
        SUITE                    SUITE
    case 'bye':              elif x == 'bye':
        SUITE                    SUITE
    case 'how are you':      elif x == 'how are you':
        SUITE                    SUITE
    else:                    else:
        SUITE                    SUITE

Instead of including a variable reference and a == operator, both are implicitely included in switch case. While bytecode is slightly different in both implemenations, both produce the same output in slightly different code styles.

Using switch and case as the statements of choice were selected from several proposed syntax variants in PEP 275. switch and case were chosen because it seems the most familiar compared to other languages.

How do I try it?!

Follow the build instructions in README.rst and run the resulting executable python.

or simply

./configure
make

About

The Python programming language with switch case!

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Python 63.9%
  • C 28.9%
  • Objective-C 4.4%
  • C++ 1.2%
  • HTML 0.4%
  • M4 0.4%
  • Other 0.8%