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:...
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…
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/")
…
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 …
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.…
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…
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…
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…
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). …