Lee Fleming wrote: > Hello, > I have a simple question. Say you have the following function: > > def f(x, y = []): ...
> But this, the code that "fixes" the list accumulation confounds me: > def f(x, y=None): > if y is None: y = [] ... > In other words, what's going on here? How is it that y accumulates > argument values between function calls in the first function, but > doesn't in the second one? I think the important thing to understand here is the distinction between names/variables and objects/values in Python. While you could interpret C code like this... void f() { ... int i = 5; ... int j = i; ... } ... as "create a place in the namespace of the f function where you can fit an integer value, and put the value 5 there. Later, create another place in the namespace of f which is also big enough for an integer. Copy the contents of the location named 'i', to the location named 'j'." You would instead interpret this similar Python code... def f(): ... i = 5 ... j = i ... ... as "create an integer object with the value 5. Then define a name/tag/variable in the namespace of function f which refers to the integer object with the value 5. Later, make a new name/tag/variable in the namespace of f which refers to the same object (happens to be an integer with the value 5) as i refers to." The semantics is very different. If you understand this, Python will seem much less magical, and you will never ask meaningless questions as whether Python uses call by reference or call by value. It's all a matter of understanding that all the juicy bits in the Python data model is in the actual values or objects. That's the stuff with type safety, a location in memory, qualities such as mutability etc. A "variable" is basically just a reference to an arbitrary object in a particular namespace. Assignments semantics is not about copying data as in C, and it's nothing arbitrarily defined in classes as in C++. It's all about deciding which object a name refers to. -- http://mail.python.org/mailman/listinfo/python-list