undecorated icon indicating copy to clipboard operation
undecorated copied to clipboard

Can't undecorate when decorated function is a closure itself

Open six8 opened this issue 8 years ago • 3 comments

When you decorate a function that is defined within another function and it references variables within the enclosing function (in other words, when you decorate a closure), you can't undecorate it.

def decorator(o):
    def foo():
        return o()
    return foo

def factory():
    outside = object()

    @decorator
    def internal_reference():
        inside = object()
        print inside

    @decorator
    def external_reference():
        return outside

    print undecorated(internal_reference)
    print undecorated(external_reference)

factory()

Output:

<function internal_reference at 0x10c30e2a8>
None

I couldn't find a way around this other than "don't do it". I ran it to while using a factory function for unit tests. This isn't typical usage of Python though.

six8 avatar Nov 11 '16 20:11 six8

I have create a PR to fix this

lkk2003rty avatar Mar 02 '17 13:03 lkk2003rty

Sorry, I missed the notification for when this issue was first opened. I'll look into this over the weekend and try to add a test before merging the fix.

iartarisi avatar Mar 10 '17 09:03 iartarisi

I've had a look at this and have pushed a fix for the simple case. However, I haven't yet found a fix for when the closure closes over a function/method. I've added some failing tests for that.

I know this is like four months too late, but it would be great to hear if this works for you, @six8.

iartarisi avatar Mar 12 '17 14:03 iartarisi