scope of function parameters (take two)

Daniel Kluev dan.kluev at gmail.com
Mon May 30 21:11:17 EDT 2011


On Tue, May 31, 2011 at 11:28 AM, Henry Olders <henry.olders at mcgill.ca> wrote:
> What I would like is that the variables which are included in the function definition's parameter list, would be always treated as local to that function

You still mis-reading docs and explanations you received from the list.
Let me try again.

First, there are objects and names. Calling either of them as
'variables' is leading to this mis-understanding. Name refers to some
object. Object may be referenced by several names or none.

Second, when you declare function `def somefunc(a, b='c')` a and b are
both local to this function. Even if there are some global a and b,
they are 'masked' in somefunc scope.
Docs portion you cited refer to other situation, when there is no
clear indicator of 'locality', like this:

def somefunc():
     print a

In this - and only in this - case a is considered global.

Third, when you do function call like somefunc(obj1, obj2) it uses
call-by-sharing model. It means that it assigns exactly same object,
that was referenced by obj1, to name a. So both obj1 and _local_ a
reference same object. Therefore when you modify this object, you can
see that obj1 and a both changed (because, in fact, obj1 and a are
just PyObject*, and point to exactly same thing, which changed).

However, if you re-assign local a or global obj1 to other object,
other name will keep referencing old object:

obj1 = []

def somefunc(a):
     a.append(1) # 'a' references to the list, which is referenced by
obj1, and calls append method of this list, which modifies itself in
place
     global obj1
     obj1 = [] # 'a' still references to original list, which is [1]
now, it have no relation to obj1 at all

somefunc(obj1)

-- 
With best regards,
Daniel Kluev



More information about the Python-list mailing list