Unexpected python exception

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Nov 13 07:07:21 EST 2009


En Wed, 11 Nov 2009 11:11:31 -0300, Ralax <ralaxmyself at gmail.com> escribió:
> On Nov 11, 6:59 pm, Richard Purdie <rpur... at rpsys.net> wrote:

>> def B():
>>     os.stat("/")
>>     import os
>>
>> 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?
>
> One word, Python treat objects in a function or method-scope as
> locals.

Not exactly; from the Language Reference [1]:

"The following constructs bind names: formal parameters to functions,
import statements, class and function definitions (these bind the class or
function name in the defining block), and targets that are identifiers if
occurring in an assignment, for loop header, or in the second position of
an except clause header. The import statement of the form “from ...import
*” binds all names defined in the imported module, except those beginning
with an underscore. This form may only be used at the module level. [...]
If a name binding operation occurs anywhere within a code block, all uses
of the name within the block are treated as references to the current
block. This can lead to errors when a name is used within a block before
it is bound. This rule is subtle. Python lacks declarations and allows
name binding operations to occur anywhere within a code block. The local
variables of a code block can be determined by scanning the entire text of
the block for name binding operations."

> So os is not defined in B(), is it right?

"os" is a local name due to import, and starts uninitialized; using it
before it is initialized raises UnboundLocalError

[1] http://docs.python.org/reference/executionmodel.html

-- 
Gabriel Genellina




More information about the Python-list mailing list