[issue35069] Unexecuted import in function causes UnboundLocalError

James Hewitt report at bugs.python.org
Thu Oct 25 16:48:04 EDT 2018


James Hewitt <jgh at caurinus.com> added the comment:

So just the fact that somewhere in the function a name is referenced, 
even if that code isn't actually executed, is enough to change the local 
namespace.  I think I knew that, but didn't know that's what it meant :)

I guess the moral is, pay attention to scope when importing submodules 
dynamically.

Thanks for looking at this, sorry it wasn't a bit more interesting :)

-James

On 10/25/2018 01:32 PM, Steven D'Aprano wrote:
> 
> Steven D'Aprano <steve+python at pearwood.info> added the comment:
> 
> Yes, that's exactly right. That's how local variables work in Python:
> 
> x = 999  # global x
> def demo():
>     if False:
>         x = 1
>     x  # local x has no value
> 
> does the same thing. This is standard, documented behaviour, regardless
> of which kind of assignment statement you use.
> 
> ----------
> 
> _______________________________________
> Python tracker <report at bugs.python.org>
> <https://bugs.python.org/issue35069>
> _______________________________________
>

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue35069>
_______________________________________


More information about the Python-bugs-list mailing list