1

Possible Duplicate:
Read/Write Python Closures

In the following function, the internal function does not modify the argument but just modifies the copy.

def func():
  i = 3
  def inc(i):
    i = i + 3
  print i
  inc(i)
  inc(i)
  print i

func()

Is it possible to avoid repeated code and put that inside a function in python? I tried the following too but it throws error UnboundLocalError: local variable 'i' referenced before assignment

def func():
  i = 3
  def inc():
    i = i + 3
  print i
  inc()
  inc()
  print i

func()
Community
  • 1
  • 1
balki
  • 26,394
  • 30
  • 105
  • 151

3 Answers3

3

In python 3 you'd do this:

def func():
  i = 3
  def inc():
    nonlocal i
    i = i+3
  print(i)
  inc()
  inc()
  print(i)

func()

In python 2.x using global doesn't work because the variable is in an outer scope, but it's not global. Hence, you'll need to pass the variable as an argument.

This is the problem that PEP 3104 addresses.

jcollado
  • 39,419
  • 8
  • 102
  • 133
2

what about:

def func():
    i = 3
    def inc(i):
        return i + 3
    print i
    i = inc(i)
    i = inc(i)
    print i

func()
hlt
  • 6,219
  • 3
  • 23
  • 43
0

In Python 3 you can use nonlocal.

>>> def func():
    i = 3
    def inc():
        nonlocal i
        i += 3
    print(i)
    inc()
    inc()
    print(i)

>>> func()
3
9
>>> 
yak
  • 8,851
  • 2
  • 29
  • 23