Weird import behavior
Duncan Booth
duncan.booth at invalid.invalid
Tue Oct 25 13:23:53 EDT 2005
Tommytrojan wrote:
> import string
> import os
>
> class T:
> def __init__(self):
> try:
> print 'xxx nothing to do'
> except ImportError:
> print 'got an import error'
> import os as string
>
> print 'xxxx string module', string
>
> t=T()
>
>
> The import clause in the except statement (although never executed)
> removes the reference to the string module imported at the beginning of
> the script. Any idea why this is the case?
Quoting the error message would have made the answer instantly clear to
everyone, including probably yourself:
UnboundLocalError: local variable 'string' referenced before assignment
Assigning to the variable 'string' anywhere in the function makes it a
local variable throughout the function. Use 'global string' if you want the
import to affect the global variable.
More information about the Python-list
mailing list