Function parameter scope
Steven D'Aprano
steve-REMOVE-THIS at cybersource.com.au
Wed Jul 28 22:51:42 EDT 2010
On Thu, 29 Jul 2010 07:30:34 +0530, Navkirat Singh wrote:
> Hi,
>
> I had another question:
>
> What is the scope of a parameter passed to a function? I know its a
> very basic question, but I am just sharpening my basics :)
>
> def func_something(x)
> return print(x+1);
>
> Does x become a local variable or does it stay as a module scoped
> variable?
>
> Though I think its local, but just want to be sure.
Yes, x is local.
However, be careful that Python does not make a copy of arguments passed
to functions. So the local name refers to the same underlying object as
the global name, and *modifications* to the *object* will be seen
everywhere. But *reassignments* to the *name* are only seen locally.
def test(local_name):
print(local_name)
local_name = 2
print(local_name)
print(global_name)
global_name = 1
test(global_name)
=> prints 1, 2, 1.
def test(local_name):
print(local_name)
local_name.append(2)
print(local_name)
print(global_name)
global_name = [1]
test(global_name)
=> prints [1], [1, 2], [1, 2].
--
Steven
More information about the Python-list
mailing list