Is this a bug?

Chris Angelico rosuav at gmail.com
Mon Jul 15 18:05:59 CEST 2013


On Tue, Jul 16, 2013 at 1:50 AM, Jack Bates <tdhfwh at nottheoilrig.com> wrote:
> Hello,
>
> Is the following code supposed to be an UnboundLocalError?
> Currently it assigns the value 'bar' to the attribute baz.foo
>
>    foo = 'bar'
>    class baz:
>       foo = foo
> --
> http://mail.python.org/mailman/listinfo/python-list

Unless you're creating that class inside a function, it would be
NameError, not UnboundLocalError. Due to the way class scopes work,
it's actually possible and sometimes useful to do this, as it
"snapshots" the current referent of that name. It's like what happens
with default arguments to a function:

foo = 'bar'
def func(foo=foo):
    return foo
foo = 'quux'

print(func())

The newly-defined name isn't "in scope" until its assignment is
complete; until then, the old name is fully in scope.

ChrisA



More information about the Python-list mailing list