Function parameter scope

Discussion in 'Python' started by Navkirat Singh, Jul 29, 2010.

  1. 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
     
    Navkirat Singh, Jul 29, 2010
    #1
    1. Advertising

  2. 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
     
    Steven D'Aprano, Jul 29, 2010
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Paul Opal
    Replies:
    12
    Views:
    961
    Paul Opal
    Oct 11, 2004
  2. J Kenneth King

    function parameter scope python 2.5.2

    J Kenneth King, Nov 20, 2008, in forum: Python
    Replies:
    11
    Views:
    585
    Terry Reedy
    Nov 21, 2008
  3. Mister B
    Replies:
    8
    Views:
    554
    Nick Keighley
    Aug 26, 2010
  4. AzamSharp
    Replies:
    2
    Views:
    181
  5. Andrew Falanga
    Replies:
    2
    Views:
    202
    Andrew Falanga
    Nov 22, 2008
Loading...

Share This Page