New submission from Martin Meo <martin....@gmail.com>:

"""
Unexpected behavior report

Dictionary get(key, default-expression) not short circuit behavior

MacOS 10.14.6
sys.version_info(major=3, minor=6, micro=5, releaselevel='final', serial=0)

BACKGROUND
A python dictionary is a data structure that associates a set of keys with a 
set of values.
Accessing a non-existent key produces a KeyError.
Dictionaries have a get() method.
get(key[, default-expression])
Return the value for key if key is in the dictionary, else default-expression.
If default-expression is not given, it defaults to None, so that this method 
never raises a KeyError.

EXPECTED BEHAVIOR
get() would only evaluate default-expression if it has to, when key is not 
found.  It would have short-circuit behavior like boolean operators.

ACTUAL BEHAVIOR
The default-expression DOES get evaluated even when the key IS found in the 
dictionary. And if default-expression is a function call, the function DOES get 
called.

"""

denominations = {0:'zero', 1:'one', 2:'two', 3:'three', 4:'four'}
        
def foo(n):
    print('FOO CALLED. n =', n)
    return str(n*10)

words = []
words.append(denominations[1])
words.append(denominations[4])
words.append(denominations.get(1))
words.append(denominations.get(4))
words.append(denominations.get(1, 'ERROR-A'))
words.append(denominations.get(4, 'ERROR-B'))

words.append(denominations.get(22, 'ERROR-1'))
words.append(denominations.get(88, 'ERROR-2'))

words.append(denominations.get(1, foo(1)))
words.append(denominations.get(4, foo(4)))

print(words)



def isItZero(n):
    print('ISITZERO CALLED.  n=', n)
    return False

a = (True or isItZero(9))   # (True or x) is always True so x is not evaluated

----------
messages: 358602
nosy: martinmeo
priority: normal
severity: normal
status: open
title: Dictionary get(key, default-expression) not short circuit behavior
type: behavior
versions: Python 3.7

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue39083>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to