[BangPypers] wierd class behavior

steve steve at lonetwin.net
Tue Dec 4 12:06:15 CET 2012


On Tuesday 04 December 2012 10:55 AM, Anand Chitipothu wrote:
>>
>> What is really weird is that the class body is evaluated without
>> considering the enclosed scope, but the methods defined in the class
>> have access to the enclosed scope.
>
> Found the culprit. Lets looks at the following code.
>
> code = """
> x = x+1
> def f():
>      return x
> print(x, f())
> """
>
> x = 5
> exec(code)
>
> x = 5
> exec(code, globals(), {})
>
> When exec is called without any locals, it works as we expected and x
> in f is bound to the x in the code.
>
> But when we supply a locals dict to exec, it behaves differently. The
> x in f is bound to global x.
>
> I'm not sure why we have this confusing behavior.
>

Here's your answer:

http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules

cheers,
- steve


More information about the BangPypers mailing list