UnboundLocalError with extra code after return

Duncan Booth duncan.booth at invalid.invalid
Wed Sep 30 03:20:25 EDT 2009


Rich Healey <healey.rich at gmail.com> wrote:

> It seems that my problem was that I can't assign a new function to the
> name func within the callonce() function. I can however interact with
> the func object (in this case storing information about whether or not
> I'd called it in it's __RECALL item.
> 
> Is there a cleaner solution?
> 

You want to call something, and have that something remember state between 
each call? If it was me I'd define a class rather than a function.

>> class CallableOnlyOnce(object):
    def __init__(self, func):
        self.func = func
    def __call__(self):
        f = self.func
        if f:
            self.func = None
            return f()

        
>>> def callonce(func):
	return CallableOnlyOnce(func)

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

    
>>> t2()
T2 called
>>> t2()
>>> 



More information about the Python-list mailing list