UnboundLocalError with extra code after return

Chris Rebert clp2 at rebertia.com
Wed Sep 30 00:41:38 EDT 2009


On Tue, Sep 29, 2009 at 9:15 PM, Rich Healey <healey.rich at gmail.com> wrote:
> However:
>
> def callonce(func):
>    def nullmethod(): pass
>    def __():
>        return func()
>        func = nullmethod

When Python sees this assignment to func as it compiles the __()
method, it marks func as a local variable and will not consult nested
function scopes when looking it up at runtime.
Hence, when the function is executed, Python does a fast lookup of
func in the local scope, finds it has not been assigned to, and raises
the error you're seeing, not falling back to and examining the outer
function variable scope.

Additionally, the __() method does not make sense as written, for its
body will stop executing as soon as it hits the first `return`
statement.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list