Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python immutable default parameters

'What You Wrote: '
def append_to(element, to=[]):
    to.append(element)
    return to
'What You Might Have Expected to Happen: '
my_list = append_to(12)
print(my_list)

my_other_list = append_to(42)
print(my_other_list)
#OUTPUT
[12]
[42]

'What Actually Happens'
[12]
[12, 42]

'''
Python’s default arguments are evaluated once when the 
function is defined, not each time the function is called 
(like it is in say, Ruby). This means that if you use a mutable 
default argument and mutate it, you will and have mutated that 
object for all future calls to the function as well.
'''

'''
What You Should Do Instead
Create a new object each time the function is called, 
by using a default arg to signal that no argument was provided 
(None is often a good choice).
'''
def append_to(element, to=None):
    if to is None:
        to = []
    to.append(element)
    return to
Comment

PREVIOUS NEXT
Code Example
Python :: what do i do if my dog eats paper 
Python :: Ascending discending 
Python :: `12` print () 
Python :: python spamming bot 
Python :: python initialize list length n 
Python :: sort list of files by name python 
Python :: how to download python freegames 
Python :: how to add stylesheet in django 
Python :: # load multiple csv files into dataframe 
Python :: combine date and time python 
Python :: scikit normalize 
Python :: read csv boto3 
Python :: erreur install pyaudio 
Python :: numpy array heaviside float values to 0 or 1 
Python :: python pandas reading pickelt 
Python :: find python path windows 
Python :: histogram seaborn 
Python :: python tkinter text widget 
Python :: combining 2 dataframes pandas 
Python :: yapf ignore line 
Python :: guido van rossum net worth 
Python :: how to write in google chrome console in python 
Python :: how to get started with python 
Python :: print decimal formatting in python 
Python :: how to print 69 in python 
Python :: error 401 unauthorized "Authentication credentials were not provided." 
Python :: seasonal_decompose python 
Python :: Access the Response Methods and Attributes in python Show Status Code 
Python :: check version numpy 
Python :: pytest installation windows 
ADD CONTENT
Topic
Content
Source link
Name
9+8 =