Why does Python sometimes not create new objects for function arguments? -
i assumed whenever passed object function, automatically created separate copy you modify without changing original. however, following code terminates error every time.
>>> testvar = ['a' in range(100000)] >>> def func(arg): while arg testvar: arg.pop() >>> func(testvar) traceback (most recent call last): file "<pyshell#47>", line 1, in <module> thing(m) file "<pyshell#43>", line 3, in thing obj.pop() indexerror: pop empty list
from: https://docs.python.org/3.4/library/copy.html
assignment statements in python not copy objects, create bindings between target , object. collections mutable or contain mutable items, copy needed 1 can change 1 copy without changing other. module provides generic shallow , deep copy operations (explained below).
when calling function, doing following:
func(arg=testvar)
if want have actual copy of data modify function following:
def func(arg): arg_copy = arg[:] # mutate arg_copy here without mutating arg
Comments
Post a Comment