UnboundLocalError with extra code after return

Rich Healey healey.rich at gmail.com
Wed Sep 30 06:15:54 CEST 2009


I'm trying to write a decorator that causes a function to do nothing
if called more than once- the reason for this is trivial and to see if
I can (Read- I'm enjoying the challenge, please don't ruin it for me
=] )

However I'm getting strange results with Python 2.6.2 on win32.

With this code:

def callonce(func):
    def nullmethod(): pass
    def __():
        return func()
    return __
@callonce
def t2():
    print "T2 called"
t2()

It does exactly what you'd expect, prints "T2 called"

However:

def callonce(func):
    def nullmethod(): pass
    def __():
        return func()
        func = nullmethod
        return ret
    return __

@callonce
def t2():
    print "T2 called"
t2()

Gives me:

C:\tmp\callonce>callonce.py
Traceback (most recent call last):
  File "C:\tmp\callonce\callonce.py", line 27, in <module>
    t2()
  File "C:\tmp\callonce\callonce.py", line 12, in __
    return func()
UnboundLocalError: local variable 'func' referenced before assignment

Any ideas on why? This looks like a bug to me, but I'm quite new to
this style of programming so it may be some nuance I'm not aware of.

Thanks in advance.

Rich Healey



More information about the Python-list mailing list