[Solved] A better way to write python closures? [closed]


Sure, you can do:

def italic(predecessor):
    x = predecessor
    def successor():
        return "<italic/>" + x() + "</italic>"
    return successor

Just like you can do:

def italic(predecessor):
    x = predecessor
    x2 = x
    def successor():
        return "<italic/>" + x2() + "</italic>"
    return successor

or

def italic(predecessor):
    x = predecessor
    x2 = x
    x3 = x2
    def successor():
        return "<italic/>" + x3() + "</italic>"
    return successor

But why would you want to?


The best way to write decorators is with functools.wraps:

from functools import wraps

def italic(f):
    @wraps(f)
    def decorated():
        return "<italic/>" + f() + "</italic>"
    return decorated

But if you really want to be different:

import functools

def italic(f):
    return functools.update_wrapper(lambda: "<italic/>" + f() + "</italic>", f)

8

solved A better way to write python closures? [closed]