tangle
tangle

Reputation: 11

How to implement Python functools.wraps equivalent?

I know I can wrap functions in Go through returning function, bug how to implement Python functools.wraps equivalent in Go? How to attach attribute to functions in Go? Like the code below in Python.

from functools import wraps

def d(f):
    def wrapper(*args):
        f(*args)

    return wrapper

def d_wraps(f):
    @wraps(f)
    def wrapper(*args):
        f(*args)

    return wrapper

@d
def f(a=''):
    print a

@d_wraps
def g(a=''):
    print a

if __name__ == '__main__':
    print 'function name: ', f.__name__
    f('abc')

    print 'function name: ', g.__name__
    g('abc')

d does not change function name, d_wraps changes function name. The result is

function name:  wrapper
abc
function name:  g
abc

I want to use the wrapped function as key at runtime. So I want to keep the function name unchanged after wrapped. How to implement the job that d_wraps does in Go?

Upvotes: 0

Views: 261

Answers (1)

bronze man
bronze man

Reputation: 1607

How to attach attribute to functions in Go?

No, You can not attach attribute to functions in Go.

How to implement the job that d_wraps does in Go?

You can implement another function call your functions, and call the function with the new name.

package main

import "fmt"

func main() {
   g_warp("abc")
}

func g(a string){
   fmt.Println(a);
}

func g_warp(a string){
   g(a+"_mysuffix");
}

If you want to change the function content but use the same function name, you can use global function variable:

package main

import (
    "fmt"
)

func main() {
    g = gV2
    g("hello")
}

var g = gV1;

func gV1(a string){
    fmt.Println(a)
}
func gV2(a string){
    gV1(a+"_suffix")
}

If you have a lot of functions to have the same wrap logic, you can pass in the origin function and return the new function:

package main

import (
    "fmt"
)

func main() {
    g = wrap(g)
    g("hello")
    f = wrap(f)
    f("hello")
}

var g = gV1;

func gV1(a string){
    fmt.Println(a)
}
var f = fV1;

func fV1(a string){
    fmt.Println(a+" "+a)
}
func wrap(originFn func(a string)) func(a string){
    return func(a string){
         originFn(a+"_suffix")
    }
}

Upvotes: 1

Related Questions