0

This is in Python 2.7. Here's an example.

v = 1

def print_v():
    v += 1
    print v

print_v()

How can this be rewritten that when this module is imported, I don't get this:

$ python -c "import the_above_module"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "the_above_module.py", line 9, in <module>
    print_v()
  File "the_above_module.py", line 6, in print_v
    v += 1
UnboundLocalError: local variable 'v' referenced before assignment
Brigand
  • 84,529
  • 20
  • 165
  • 173
  • Search for `[python]UnboundLocalError`. Or click [here](http://stackoverflow.com/a/9264845/1217270), [here](http://docs.python.org/3.3/faq/programming.html#core-language), or [here](http://stackoverflow.com/q/423379/1217270). – Honest Abe Feb 23 '13 at 21:50
  • I looked at a few, but somehow missed those. Thanks :-) – Brigand Feb 23 '13 at 22:02

1 Answers1

4

Put global v inside your print_v function.

However, you should think about why you're using (and modifying) a global variable. It is often a fragile way to do things.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • Thanks. I have a StringIO instance that's written to by other scripts of the module, and I want to keep a consistent reference available. The main module file only handles the reference to the StringIO, resetting it, and returning the value. Any recommendations on how else to do it? – Brigand Feb 23 '13 at 22:04