osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Instance vs Class variable oddity


Chris Angelico? 2019?5?18???? UTC+8??3?09?37????
> On Sat, May 18, 2019 at 1:51 PM <jfong at ms4.hinet.net> wrote:
> >
> > Correct me if I am wrong, please.
> >
> > I always think that the LEGB rule (e.g. the namespace to look up for) was applied at compile-time, only the binding was resolved "dynamically" at run-time. For example:
> >
> > def foo():
> >     print(x)
> >
> > foo() will cause a NameError. But after
> >
> > x = 5
> >
> > foo() will run correctly.
> 
> This is correct; however, this function will fail with UnboundLocalError:
> 
> x = 1
> def foo():
>     print(x)
>     x = 2
> 
> Function locals ARE locked in at compile time.
> 
> ChrisA

Thank you. This example proves that the LEGB rule was applied at compile-time, and it fails to resolve the binding at run-time.

--Jach