How to make a new default argument list every time [duplicate]

2024/10/9 1:40:40

I have the following setup:

def returnList(arg=["abc"]):return arglist1 = returnList()
list2 = returnList()list2.append("def")print("list1: " + " ".join(list1) + "\n" + "list2: " + " ".join(list2) + "\n")print(id(list1))
print(id(list2))

Output:

list1: abc def
list2: abc def140218365917160
140218365917160

I can see that arg=["abc"] returns copy of the same default list rather than create a new one every time.

I have tried doing

def returnList(arg=["abc"][:]):

and

def returnList(arg=list(["abc"])):

Is it possible to get a new list, or must I copy the list inside the method everytime I want to some kind of default value?

Answer

The nicest pattern I've seen is just

def returnList(arg=None):if arg is None: arg = ["abc"]...

The only potential problem is if you expect None to be a valid input here which in which case you'll have to use a different sentinel value.

The problem with your approach is that args default argument is evaluated once. It doesn't matter what copying operators you do because it's simply evaluated than stored with the function. It's not re-evaluated during each function call.

Update:

I didn't want nneonneo's comment to be missed, using a fresh object as a sentinel would work nicely.

default = object()
def f(x = default):if x is default:...
https://en.xdnf.cn/q/118564.html

Related Q&A

How does one reorder information in an XML document in python 3?

Lets suppose I have the following XML structure:<?xml version="1.0" encoding="utf-8" ?> <Document><CstmrCdtTrfInitn><GrpHdr><other_tags>a</other_t…

Python - Replace only exact word in string [duplicate]

This question already has answers here:How to match a whole word with a regular expression?(4 answers)Closed 4 years ago.I want to replace only specific word in one string. However, some other words h…

How to write Hierarchical query in PYTHON

The given input is like:EMPLOYEE_ID NAME MANAGER_ID101 A 10102 B 1110 C 111 D 11 E nullEmployee Cycle LEVEL Path10…

Unable to launch selenium with python in mac

Im facing an issue with selenium with python in Mac OS.. Python 2.7 pydev 3.0My sample codefrom selenium import webdriver driver = webdriver.Firefox() driver.get("https://www.formsite.com/") …

Memory error In instantiating the numpy array

I have a list A of a 50,000 elements and each element is an array of shape (102400) I tried instantiating an array B.B=numpy.array(A)But this throws an exception MemoryError.I know that the memory and …

Setting column names in a pandas dataframe (Python)

When setting a column name for a pandas dataframe, why does the following work:df_coeff = pd.DataFrame(data = lm.coef_, index = X.columns, columns = [Coefficient])While this does not workdf_coeff = pd.…

Check that Python function does not modify argument?

You know how in Python, if v is a list or a dictionary, its quite common to write functions that modify v in place (instead of just returning the new value). Im wondering if it is possible to write a c…

What Python 3 version for my Django project

I will try to port my Python 2.7 with Django to Python 3. But now my question is what version is the most stable one today? Ive heard people use 3.2 and 3.4 and recommend it. But now Im asking you guy…

Error during runfile in Eclipse with PyDev/ error initializing console

Using a PyDev console in Eclipse, which initially worked fine. Python code would work inside the console. When I started writing a file within a PyDev module, I tried executing runfile() but the consol…

Reversibly encode two large integers of different bit lengths into one integer

I want to encode two large integers of possibly different maximum bit lengths into a single integer. The first integer is signed (can be negative) whereas the second is unsigned (always non-negative). …