0

The following code runs without errors.

import kivy
def main():
    try:
        kivy.require('1.9.2')
    except Exception as e:
        import traceback
        traceback.print_exc()
        #import kivy.base
if __name__ in ('__main__'):
    main()

However, if I un-comment line 8, it prints:

 Traceback (most recent call last):
   File "main.py", line 4, in main
     kivy.require('1.9.2')
 UnboundLocalError: local variable 'kivy' referenced before assignment

I have two questions:

  1. Why is kivy on line 4 recognized as a variable instead of a module?
  2. How does line 8 affect whether line 4 raises an exception?
bitinerant
  • 1,168
  • 7
  • 24
  • This is answered by a combination of https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use and https://nedbatchelder.com/text/names1.html . – Karl Knechtel May 11 '20 at 21:52

1 Answers1

0

I think you've hit the standard global/local behaviour described e.g. in this answer, but obfuscated slightly by the fact that you're assigning to the variable via importing.

Note that the kivy variable isn't special just because you assigned to it via an import, it's still a variable name that follows normal reassignment and referencing rules.

inclement
  • 29,124
  • 4
  • 48
  • 60
  • I was hoping for an answer with more detail, but I'll accept this. You're right - it's the global/local issue. To make it do what I intended, I needed to add `global kivy` just before the `kivy.require()` line. – bitinerant May 19 '20 at 09:12