Unexpected python exception

Ralax ralaxmyself at gmail.com
Wed Nov 11 09:11:31 EST 2009


On Nov 11, 6:59 pm, Richard Purdie <rpur... at rpsys.net> wrote:
> I've been having problems with an unexpected exception from python which
> I can summarise with the following testcase:
>
> def A():
>     import __builtin__
>     import os
>
>     __builtin__.os = os
>
> def B():
>     os.stat("/")
>     import os
>
> A()
> B()
>
> which results in:
>
> Traceback (most recent call last):
>   File "./test.py", line 12, in <module>
>     B()
>   File "./test.py", line 8, in B
>     os.stat("/")
> UnboundLocalError: local variable 'os' referenced before assignment
>
> If I remove the "import os" from B(), it works as expected.
>
> >From what I've seen, its very unusual to have something operate
>
> "backwards" in scope in python. Can anyone explain why this happens?
>
> Cheers,
>
> Richard

One word, Python treat objects in a function or method-scope as
locals.
So os is not defined in B(), is it right?



More information about the Python-list mailing list