Function parameter scope

N

Navkirat Singh

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.

Thanks,
Nav
 
S

Steven D'Aprano

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].
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,740
Latest member
AdolphBig6

Latest Threads

Top