Benjamin Bennett Alexander’s Post

🔺 BIG Python Sin: Using a mutable default argument Don't use a mutable object as a default argument. Default arguments in Python are evaluated once, at function definition time, not each time the function is called. If you have a default argument like: items=[], it will be shared across all calls, and you will get an accumulating state you didn’t ask for. # Mutable default argument def add_item(item, my_list=[]):     my_list.append(item)     return my_list Output print(add_item(1))  # [1] print(add_item(2))  # [1, 2] print(add_item(3))  # [1, 2, 3] 👑 The best way is to have an immutable object as a default argument. That way, each call will get a fresh list as in the example below. def add_item(item: int, my_list: Optional[List[int]] = None) -> List[int]: if my_list is None: my_list = [] my_list.append(item) return my_list Default arguments are evaluated at function definition time, not call time. When in doubt, use None as the default and create the mutable object inside the function! Learn About Python classes. Full Classes video on YouTube. Link below Link: https://lnkd.in/eJ_zMQis

  • text

It depends on use case. Mutable defaults is okay as long as either: 1. We are not making any changes to it: like the below example: def check_item_in_list(item, my_list=[]): return item in my_list #... Not adding, or removing, or modifying anything 2. We really want to make changes to that mutable real-time as and when the function is called, like the first example in this post If we are making changes to the mutable, but want to retain the default behaviour of the mutable (specified during function definition) when we are calling the function without specifying its value, which is the use case you are showing, then we should avoid using mutable defaults.

Like
Reply

To view or add a comment, sign in

Explore content categories