I implemented two simple closures in Python. To me, they looks the same, but one works and the other doesn't.
The working one is:
def makeInc(x, y):
def inc():
return y + x
return inc
inc5 = makeInc(5, 10)
inc10 = makeInc(10, 5)
inc5 () # returns 15
inc10() # returns 15
But the second one doesn't work:
import os
def linker(dest, filename):
print filename
def link():
if os.path.isfile(filename): # line 17
filename = os.path.join(os.getcwd(), filename)
dest = os.path.join(dest, filename)
y = rawinput('[y]/n: ln -sf %s %s' % (dest, filename))
if y == 'n':
return 1
else:
return os.system('ln -sf %s %s' %(dest, filename))
else:
return -1
return link
l = linker('~', '.vimrc')
l() # line 30
It faults at the first line of link()
when executing l()
:
Traceback (most recent call last):
File "test.py", line 30, in <module>
l()
File "test.py", line 17, in link
if os.path.isfile(filename):
UnboundLocalError: local variable 'filename' referenced before assignment
They seem identical to me so I don't understand why the second one doesn't work. Any idea?