简体   繁体   中英

A decorator to convert arguments of a function

I'd like to use a decorator to convert arguments of a function.

so instead of doing:

def get_data(dt, symbol, depth, session):
    dt = to_date(dt)
    ...

or

def get_data(dt, symbol, depth, session):
    dt = convert(dt, to_date)
    ...

I would like to be able to write something like

@convert('dt', to_date)
def get_data(dt, symbol, depth, session):
    ...

but I don't feel very confortable with this feature.

How to write such a decorator ?

Fiddled around with it a bit and learned quite a bit about generators:

def convert(arg, mod):
    def actual_convert(fn):
        if arg not in fn.__code__.co_varnames:
            return fn
        else:
            def new_function(*args, **kwargs):
                l_args = list(args)
                index = fn.__code__.co_varnames.index(arg)
                l_args[index] = mod(l_args[fn.__code__.co_varnames.index(arg)])
                args = tuple(l_args)
                return fn(*args, **kwargs)
            return new_function
    return actual_convert

@convert('x',lambda x: x+1)
def add(x,y):
    return x + y

print("Should be 5:",add(3,1))

This will only work with normal arguments for now, not keyword arguments. It would be fairly easy to do that, too, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM