Why are default values shared between objects in Python?


The default values concept in Python are based on using mutable or immutable objects. It is good programming practice to not use mutable objects as default values. Instead, use None as the default value to avoid issues. Immutable objects such as numbers, strings, tuples, and None, are safe from change. Changes to mutable objects such as dictionaries, lists, and class instances can lead to confusion.

Let’s see the example of a Dictionary in a function and the issues with it and how to fix it.

Problem

We have a function. In that we have a Dictionary as a parameter with a default value. The first time you call this function, mydict contains a single item. The second time, mydict contains two items because when foo() begins executing, mydict starts out with an item already in it.

def foo(mydict={}): ... calculate... mydict[key] = value return mydict

We often expect that a function call creates new objects for default values. However, this is not the case. The Default values are created exactly once, when the function is defined. If that object is changed, like the dictionary in the above example, the subsequent calls to the function will refer to this changed object.

Solution

To fix the issue with using the default values as mutable objects, like this −

def foo(mydict={}):
   ...

Use the immutable object like None −

def foo(mydict=None): if mydict is None: mydict = {}

A technique when you have a function that’s time-consuming to calculate, is to cache the parameters and the resulting value of each call to the function, and return the cached value if the same value is requested again.

This is called memoizing, and can be implemented like this −

# Callers can only provide two parameters and optionally pass _cache by keyword def expensive(arg1, arg2, *, _cache={}): if (arg1, arg2) in _cache: return _cache[(arg1, arg2)] # Calculate result = ... expensive computation ... _cache[(arg1, arg2)] = result return result

The following stores the result in the cache −

_cache[(arg1, arg2)] = result

Updated on: 19-Sep-2022

982 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements