Python - mutable variable not clearing inbetween function calls

11 Views Asked by At

Although I found two other 'answered' questions on this topic, I'm trying to understand why this happens in python and have not found an answer yet other than 'that's just how python works'

In the below example, what I want is to initialize a new memo when canSum is called without a memo provided to it. However I notice when I call the function multiple times, the contents of memo seem to be pushed forward to future function calls:

def canSum(targetSum, nums, memo = {}):
    # memo base case
    if targetSum in memo:
        return memo[targetSum]

    # base case
    if targetSum == 0: return True
    if targetSum < 0: return False

    for num in nums:
        remainder = targetSum - num
        if canSum(remainder, nums, memo):
            memo[targetSum] = True
            return True

    memo[targetSum] = False
    return False

The solution I found on stackoverflow was pretty simple:

def canSum(targetSum, nums, memo = None):
    if memo == None:
        memo = {}

    .
    .
    .

Can anyone point me to some documentation of perhaps an explanation as to why this occurs in Python?

0

There are 0 best solutions below