I am trying to provide a function as the default argument for the dictionary\'s get function, like this
def run():
print \"RUNNING\"
test = {\'store\':1
See the discussion in the answers and comments of dict.get() method returns a pointer. You have to break it into two steps.
Your options are:
Use a defaultdict
with the callable if you always want that value as the default, and want to store it in the dict
.
Use a conditional expression:
item = test['store'] if 'store' in test else run()
Use try
/ except
:
try:
item = test['store']
except KeyError:
item = run()
Use get
:
item = test.get('store')
if item is None:
item = run()
And variations on those themes.
glglgl shows a way to subclass defaultdict
, you can also just subclass dict
for some situations:
def run():
print "RUNNING"
return 1
class dict_nokeyerror(dict):
def __missing__(self, key):
return run()
test = dict_nokeyerror()
print test['a']
# RUNNING
# 1
Subclassing only really makes sense if you always want the dict
to have some nonstandard behavior; if you generally want it to behave like a normal dict
and just want a lazy get
in one place, use one of my methods 2-4.