简体   繁体   English

装饰器,用于转换函数的参数

[英]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. 不过,这样做也很容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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