it functions as expected. However if I subsequently do not explicitly pass an empty object, the value of memo from a prior call seems to be retained and used, therefore failing:
This is a common gotcha. The default values for a function’s arguments are evaluated once, when the function is defined, not every time the function is called. This means that if you have a mutable default value, any mutation will be preserved from call to call. The default value itself is attached to the function object, so it never goes out of scope.
The standard idiom for dealing with this is to use the default value of None, and check for it in the body of your function. Something like:
def canSum(targetSum, numbers, memo=None):
if memo is None:
memo = {}
Default values are created once, when the function is created, not every time you call the function. This is called “early binding” of the default value for the parameter.
So the default value for memo gets initialised once, and then the same dict object is used each time you use the default.
Thank you for pointing that out. Wouldn’t that mean that the objects stay in memory after the function call? That would be potentially problematic for large objects if I understand correctly, no?