Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PEP 3103: Difference between switch case and if statement code blocks

Tags:

python

In PEP 3103, Guido is discussing adding a switch/case statement to Python with the various schools of thought, methods and objects. In that he makes this statement:

Another objection is that the first-use rule allows obfuscated code like this:

def foo(x, y):
    switch x:
    case y:
        print 42 

To the untrained eye (not familiar with Python) this code would be equivalent to this:

def foo(x, y):
    if x == y:
        print 42

but that's not what it does (unless it is always called with the same value as the second argument). This has been addressed by suggesting that the case expressions should not be allowed to reference local variables, but this is somewhat arbitrary.

I wouldn't have considered myself untrained or unfamiliar with Python but nothing jumps out at me as these two blocks of code being different.

What is it that he is referencing that would have made these two pieces of code different in execution?

like image 398
Matthew Green Avatar asked Aug 14 '15 15:08

Matthew Green


1 Answers

You need to read the description at the beginning of that section. "The oldest proposal to deal with this is to freeze the dispatch dict the first time the switch is executed." That implies that the value of y will be cached when the switch statement first runs, such that if you first call it as:

foo(10,10)

Subsequent calls, such as foo(20,20), will actually be comparing:

switch x:
case 10:
    print 42 
like image 191
larsks Avatar answered Sep 30 '22 19:09

larsks