Femto Trader
Femto Trader

Reputation: 2014

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 ?

Upvotes: 2

Views: 932

Answers (1)

L3viathan
L3viathan

Reputation: 27273

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.

Upvotes: 4

Related Questions