[issue45294] Conditional import fails and produce UnboundLocalError, if a variable machting import name is used before

Steven D'Aprano report at bugs.python.org
Mon Sep 27 10:44:24 EDT 2021


Steven D'Aprano <steve+python at pearwood.info> added the comment:

I'm glad that you fixed the bug in your code, but this is not a bug in 
Python. It isn't "a parsing issue", the code is parsed fine. What you 
did was no different from:

    def func():
        print(x)
        x = 1

except that the binding operation was an import, not an assignment. You 
get exactly the same error here:

    def func():
        print(math)
        import math

That's the way the language is defined. Imports and assignments are both 
binding operations and are treated the same by the interpreter. It's not 
an accident or a mistake or a parsing issue or a bug, it is the way the 
language is supposed to work.

----------

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


More information about the Python-bugs-list mailing list