Best way to use module local variables in functions that modify their value?

Question:

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
Asked By: Brigand

||

Answers:

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.

Answered By: BrenBarn
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.