scope of function parameters

Chris Rebert clp2 at rebertia.com
Sun May 29 14:01:18 EDT 2011


On Sun, May 29, 2011 at 10:53 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Sun, May 29, 2011 at 10:47 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> If a name is assigned to anywhere in the function, treat it as a local,
>> and look it up in the local namespace. If not found, raise
>> UnboundLocalError.
>>
>
> Wait wha? I've never seen this... wouldn't it just create it in the
> local namespace?
>
> Can you give example code that will trigger this error? I'm curious, now...

def foo():
    print bar
    bar = 42

foo()

===>
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'bar' referenced before assignment

Cheers,
Chris



More information about the Python-list mailing list