0

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!

rdj
  • 1
  • 1
    `import`s count as assignments. This is just a standard `UnboundLocalError`, like what you probably got the first time you tried to modify a global variable without a `global` declaration. – user2357112 Sep 10 '16 at 03:40
  • Thank you. However, the other question doesn't give me any direction on how to fix this. What sets my case apart is that I'm trying to do this on an import and not a regular assignment. I can't use "global" or "nonlocal" on a module name. I want to conditionally import from within my function. Note that even if I am importing an entirely different submodule, such as `import mymodule.mymodule3` it fails. – rdj Sep 10 '16 at 04:40
  • "I can't use "global" or "nonlocal" on a module name" - [oh really](http://ideone.com/ViSAFi)? Why are you doing the import conditionally, anyway? Particularly, why are the conditions under which you import the module different from the conditions under which you use it? – user2357112 Sep 10 '16 at 04:52
  • Or at least, I can't seem to use "global" on a module with a period in it, such as `global mymodule.module3`. The reason I am trying to load dynamically is because the module I am importing imports slowly, yet is not necessary to the core purpose of my code. – rdj Sep 10 '16 at 05:00
  • That's because you need to do `global mymodule`. – user2357112 Sep 10 '16 at 05:08

0 Answers0