I have a curious bug in my Python code (tried under both 2.7 and 3.4) that I was able to nail down to a minimal use case, and can be replicated below. Does anyone understand what is happening here?
$ ls mymodule/
mymodule2.py runner.py
$ touch mymodule/__init__.py
$ cat mymodule/mymodule2.py
import mymodule
class MyClass(object):
@staticmethod
def my_method():
pass
$ cat mymodule/runner.py
import os
import sys
testdir = os.path.dirname(__file__)
sys.path.insert(0, os.path.abspath(os.path.join(testdir, "..")))
import mymodule
import mymodule.mymodule2
def main():
mymodule.mymodule2.MyClass.my_method()
return
import mymodule
main()
This gives me this result:
Traceback (most recent call last):
File "mymodule/runner.py", line 14, in <module>
main()
File "mymodule/runner.py", line 11, in main
mymodule.mymodule2.MyClass.my_method()
UnboundLocalError: local variable 'mymodule' referenced before assignment
If I comment out the line import mymodule, everything runs without error or output. The line of code is never hit, but its existence changes what happens.
Can someone explain my gap in understanding here? Much appreciated!