scope of function parameters
Chris Rebert
crebert at ucsd.edu
Sun May 29 06:01:52 EDT 2011
On Sun, May 29, 2011 at 1:30 AM, Henry Olders <henry.olders at mcgill.ca> wrote:
> I just spent a considerable amount of time and effort debugging a program. The made-up code snippet below illustrates the problem I encountered:
>
> def main():
> a = ['a list','with','three elements']
> print a
> print fnc1(a)
> print a
>
> def fnc1(b):
> return fnc2(b)
>
> def fnc2(c):
> c[1] = 'having'
> return c
>
> This is the output:
> ['a list', 'with', 'three elements']
> ['a list', 'having', 'three elements']
> ['a list', 'having', 'three elements']
>
> I had expected the third print statement to give the same output as the first, but variable a had been changed by changing variable c in fnc2.
To be more accurate, the list object referred to by `a` was modified
through c, due to the fact that a, b, and c all refer to the very same
object in this case.
> It seems that in Python, a variable inside a function is global unless it's assigned. This rule has apparently been adopted in order to reduce clutter by not having to have global declarations all over the place.
>
> I would have thought that a function parameter would automatically be considered local to the function.
<snip>
> Are there others who feel as I do that a function parameter should always be local to the function? Or am I missing something here?
Function parameters *are* local variables. Function parameters are
indeed local in that *rebinding* them has no effect outside of the
function:
def foo(a):
a = 42
def bar():
b = 1
foo(b)
print b
bar() #=> outputs 1
As you've observed, *mutating* the object a variable refers to is
another matter entirely. Python does not use call-by-value and does
not copy objects unless explicitly requested to, as you've
encountered. But it does not use call-by-reference either, as my
example demonstrates. Like several other popular contemporary
languages, Python uses call-by-object for parameter passing; a good
explanation of this model can be found at
http://effbot.org/zone/call-by-object.htm It's well worth reading.
Cheers,
Chris
More information about the Python-list
mailing list