Is this a bug?

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

On Tue, Jul 16, 2013 at 1:50 AM, Jack Bates <tdhfwh at> wrote:
> Hello,
> Is the following code supposed to be an UnboundLocalError?
> Currently it assigns the value 'bar' to the attribute
>    foo = 'bar'
>    class baz:
>       foo = foo
> --

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'


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


More information about the Python-list mailing list