pythondictionarydefault-value

How to completely reassign a dictionary that is a default mutable value in the formal parameters of a function in python


def myfunc(l=[]):
    if not l:
        l[:] = otherlist

The preceding snippet of code completely reassigns list l to whatever list is stored in variable otherlist and maintains that value across function calls of myfunc.

def myfunc(d={}):
    
    d.clear()
    for k, v in otherd.items():
        d[k] = v

For this example assume dictionary otherd is within the scope of the function call, just not explicitly provided.

Is there a way to completely reassign dictionary d in a simpler way than the direct reassignment in the example provided?

Note:

Default mutable values is a value that is initialized and stored upon the first call of the function. When mutated it maintains that state across function calls, so when accessed it will return its most recent state rather than the initial one.


Solution

  • def myfunc(d={}):
        d.clear()
        d.update(otherd)
    

    should do the trick. That said, a mutable default argument value is often not a great idea. You probably know that and this is intentional. If not, an alternative could be

    import copy
    
    
    def myfunc(d=None):
        d = d or copy.copy(otherd)  # or copy.deepcopy, if you will.