Can local function access local variables in main program?

Discussion in 'Python' started by Sullivan WxPyQtKinter, Nov 3, 2007.

  1. I am confused by the following program:

    def f():
    print x
    x=12345
    f()

    result is:
    >>>

    12345

    however:
    def f():
    print x
    x=0

    x=12345
    f()

    result is:
    Traceback (most recent call last):
    File "...\test.py", line 5, in ?
    f()
    File "...\test.py", line 2, in f
    print x
    UnboundLocalError: local variable 'x' referenced before assignment


    I am using
    Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)]
    on win32
    I also tested it on python 2.5, which gives the same result.
    Sullivan WxPyQtKinter, Nov 3, 2007
    #1
    1. Advertising

  2. On Sat, 03 Nov 2007 07:18:17 +0000, Sullivan WxPyQtKinter wrote:

    > def f():
    > print x
    > x=0
    >
    > x=12345
    > f()
    >
    > result is:
    > Traceback (most recent call last):
    > File "...\test.py", line 5, in ?
    > f()
    > File "...\test.py", line 2, in f
    > print x
    > UnboundLocalError: local variable 'x' referenced before assignment



    When Python compiles your function f(), it sees that you have assigned to
    x, and that there is no line "global x", so it knows that x is a local
    variable.

    But when you call f(), you try to print x before the local x has a value
    assigned to it. Hence the (accurate but hardly user-friendly) error
    message.

    You can also do this:

    >>> help(UnboundLocalError)


    Help on class UnboundLocalError in module exceptions:

    class UnboundLocalError(NameError)
    | Local name referenced but not bound to a value.



    As far as I know, there is no way to read the value of global x if and
    only if local x doesn't exist.



    --
    Steven
    Steven D'Aprano, Nov 3, 2007
    #2
    1. Advertising

  3. Sullivan WxPyQtKinter

    Stargaming Guest

    On Sat, 03 Nov 2007 07:18:17 +0000, Sullivan WxPyQtKinter wrote:

    > I am confused by the following program:
    >
    > def f():
    > print x
    > x=12345
    > f()
    >
    > result is:
    >>>>

    > 12345


    If python can't discover x in your current scope and you do not bind to
    it there, it will automatically access that global name x.

    > however:
    > def f():
    > print x
    > x=0
    >
    > x=12345
    > f()
    >
    > result is:
    > Traceback (most recent call last):
    > File "...\test.py", line 5, in ?
    > f()
    > File "...\test.py", line 2, in f
    > print x
    > UnboundLocalError: local variable 'x' referenced before assignment


    Here, you *do* assign to x in this scope so this is essentially the same
    as the following (without any function scope)::

    print x
    x = 12345

    This can't work since you haven't used x when you try to print it.

    You can make this work using the `global` statement::

    >>> def foo():

    ... global x
    ... print x
    ... x = 0
    ...
    >>> x = 12345
    >>> print x

    12345
    >>> foo()

    12345
    >>> print x

    0

    See more in the `lexical reference about the global statement <http://
    docs.python.org/ref/global.html>.

    HTH,
    Stargaming
    Stargaming, Nov 3, 2007
    #3
  4. Bjoern Schliessmann, Nov 3, 2007
    #4
  5. Actually I am quite satisfied with and error, which is my expectation.
    But the implicit global variable access seems quite uncomfortable to
    me. Why is that necessary?

    On Nov 3, 3:39 am, Stargaming <> wrote:
    > On Sat, 03 Nov 2007 07:18:17 +0000, Sullivan WxPyQtKinter wrote:
    > > I am confused by the following program:

    >
    > > def f():
    > > print x
    > > x=12345
    > > f()

    >
    > > result is:

    >
    > > 12345

    >
    > If python can't discover x in your current scope and you do not bind to
    > it there, it will automatically access that global name x.
    Sullivan WxPyQtKinter, Nov 3, 2007
    #5
  6. On Sat, 03 Nov 2007 17:30:45 -0000, Sullivan WxPyQtKinter
    <> declaimed the following in comp.lang.python:

    > Actually I am quite satisfied with and error, which is my expectation.
    > But the implicit global variable access seems quite uncomfortable to
    > me. Why is that necessary?


    Would you want to have to write things like:

    import os
    import os.path
    import sys

    def dFunc(more):
    return "The full path of the item is: %s" % more

    def aFunc(something):
    global os.path
    global sys
    global dFunc
    sys.stdout.write(dFunc(os.path.join("nonsense", something)))

    Your "variable" follows the same logic used for name look ups of all
    items -- "read" access will, after exhausting the local scope, search
    the module level names (note that you don't need "global" to modify a
    mutable object in module level -- it is only the rebinding of the name
    itself that needs "global")
    --
    Wulfraed Dennis Lee Bieber KD6MOG

    HTTP://wlfraed.home.netcom.com/
    (Bestiaria Support Staff: )
    HTTP://www.bestiaria.com/
    Dennis Lee Bieber, Nov 3, 2007
    #6
  7. Sullivan WxPyQtKinter

    Pawel Guest

    Stargaming wrote:
    > You can make this work using the `global` statement::
    >
    > >>> def foo():

    > ... global x
    > ... print x
    > ... x = 0


    Is there any way to disable global for x? Something like that:
    >>> x = 12345
    >>> def foo():

    .... global x
    .... print x
    .... noglobal(x) # ???
    .... x = 0 # now this is local x
    >>> foo()

    12345
    >>> print x

    12345

    --
    In pariete - manus et crus cerebrumque
    Pawel, Nov 3, 2007
    #7
  8. Sullivan WxPyQtKinter

    Erik Jones Guest

    On Nov 3, 2007, at 5:32 PM, Pawel wrote:

    > Stargaming wrote:
    >> You can make this work using the `global` statement::
    >>
    >>>>> def foo():

    >> ... global x
    >> ... print x
    >> ... x = 0

    >
    > Is there any way to disable global for x? Something like that:
    >>>> x = 12345
    >>>> def foo():

    > ... global x
    > ... print x
    > ... noglobal(x) # ???
    > ... x = 0 # now this is local x
    >>>> foo()

    > 12345
    >>>> print x

    > 12345


    Why would you need to do that? It would be confusing. Just use a
    different variable name for the local.

    Erik Jones

    Software Developer | Emma®

    800.595.4401 or 615.292.5888
    615.292.0777 (fax)

    Emma helps organizations everywhere communicate & market in style.
    Visit us online at http://www.myemma.com
    Erik Jones, Nov 3, 2007
    #8
  9. On Sat, 03 Nov 2007 23:32:48 +0100, Pawel <>
    declaimed the following in comp.lang.python:

    > Is there any way to disable global for x? Something like that:
    > >>> x = 12345
    > >>> def foo():

    > ... global x
    > ... print x
    > ... noglobal(x) # ???
    > ... x = 0 # now this is local x


    def foo():
    lx = x
    print lx
    lx = 0

    And takes one less line even! (if you don'l like l, use local_, or
    some other convention)
    --
    Wulfraed Dennis Lee Bieber KD6MOG

    HTTP://wlfraed.home.netcom.com/
    (Bestiaria Support Staff: )
    HTTP://www.bestiaria.com/
    Dennis Lee Bieber, Nov 4, 2007
    #9
  10. Pawel wrote:
    > Is there any way to disable global for x? Something like that:
    >>>> x = 12345
    >>>> def foo():

    > ... global x
    > ... print x
    > ... noglobal(x) # ???
    > ... x = 0 # now this is local x


    Not really. Why don't you choose meaningful variable names? You
    practically save nothing by using fewer names.

    Regards,


    Björn

    --
    BOFH excuse #423:

    It's not RFC-822 compliant.
    Bjoern Schliessmann, Nov 4, 2007
    #10
  11. On 2007-11-03, Dennis Lee Bieber <> wrote:
    > On Sat, 03 Nov 2007 17:30:45 -0000, Sullivan WxPyQtKinter
    ><> declaimed the following in comp.lang.python:
    >
    >> Actually I am quite satisfied with and error, which is my expectation.
    >> But the implicit global variable access seems quite uncomfortable to
    >> me. Why is that necessary?

    >
    > Would you want to have to write things like:


    Well it would be explicit and explicit is better than implicit.

    > import os
    > import os.path
    > import sys
    >
    > def dFunc(more):
    > return "The full path of the item is: %s" % more
    >
    > def aFunc(something):
    > global os.path
    > global sys
    > global dFunc
    > sys.stdout.write(dFunc(os.path.join("nonsense", something)))
    >
    > Your "variable" follows the same logic used for name look ups of all
    > items -- "read" access will, after exhausting the local scope, search
    > the module level names (note that you don't need "global" to modify a
    > mutable object in module level -- it is only the rebinding of the name
    > itself that needs "global")


    --
    Antoon Pardon
    Antoon Pardon, Nov 8, 2007
    #11
    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. Ravi
    Replies:
    17
    Views:
    920
    Kenneth Brody
    Apr 1, 2006
  2. ravi
    Replies:
    28
    Views:
    973
    Richard Heathfield
    Sep 26, 2007
  3. Replies:
    9
    Views:
    935
  4. GogromaT
    Replies:
    0
    Views:
    477
    GogromaT
    Apr 27, 2009
  5. Sean
    Replies:
    2
    Views:
    93
Loading...

Share This Page