Let's have a method that would cache results it calculates.
"If" approach:
def calculate1(input_values):
if input_values not in calculate1.cache.keys():
# do some calculation
result = input_values
calculate1.cache[input_values] = result
return calculate1.cache[input_values]
calculate1.cache = {}
"Except" approach:
def calculate2(input_values):
try:
return calculate2.cache[input_values]
except AttributeError:
calculate2.cache = {}
except KeyError:
pass
# do some calculation
result = input_values
calculate2.cache[input_values] = result
return result
"get/has" approach:
def calculate3(input_values):
if not hasattr(calculate3, cache):
calculate3.cache = {}
result = calculate3.cache.get(input_values)
if not result:
# do some calculation
result = input_values
calculate3.cache[input_values] = result
return result
Is there another (faster) way? Which one is most pythonic? Which one would you use?
Note: There's a speed difference:
calculate = calculateX # depening on test run
for i in xrange(10000):
calculate(datetime.utcnow())
Results time python test.py
:
calculate1: 0m9.579s
calculate2: 0m0.130s
calculate3: 0m0.095s
Using fromkeys() function If you want to initialize all keys in the dictionary with some default value, you can use the fromkeys() function. If no default value is specified, the dictionary is initialized with all values as None .
default defaults to None . Return the value for key if key is in the dictionary, else default . If default is not given, it defaults to None , so that this method never raises a KeyError . In the above code, you use .
Python Dictionary setdefault() returns the value of a key (if the key is in dictionary). Else, it inserts a key with the default value to the dictionary.
Another way to initialize a python dictionary is to use its built-in “dict()” function in the code. So, you have to declare a variable and assign it the “dict()” function as an input value. After this, the same print function is here to print out the initialized dictionary.
Use a collections.defaultdict. It's designed precisely for this purpose.
Of course; this is Python after all: Just use a defaultdict.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With