0

I have a Pandas Time Series that I would like to "format", in the sense that I have an offset of days and I want to only output the series for days above the offset. Indeed, this can be done by a simple line of code:

series = series.iloc[offset:]

But I have a lot of cases where this needs to be done so I'd prefer having something more modular. I have only just started getting into decorators so I still am finding them quite hard to grasp, however, I thought about writing a decorator as follows:

def apply_offset(series, days):
    def adj(*args, **kwargs):
        return series(*args, **kwargs).iloc[days:]
    return adj

And then apply it to some function that returns a series like so:

@apply_offset(200)
def ret_series(*args, **kwargs):
    # returns a series

So in the above example the series is applied with an offset of 200 days. Now this raises an error when the interpreter arrives at the decoration, namely:

TypeError: apply_offset() missing 1 required positional argument: 'offset'

What am I doing wrong?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
mesllo
  • 545
  • 7
  • 29

1 Answers1

2

Decorator must accept function as the only argument. But you can return such decorator function by constructing it with parameters you need.

def apply_offset(days):
    def wrapper(function):
        def wrapped(*args, **kwargs):
            return function(*args, **kwargs).iloc[days:]
        return wrapped
    return wrapper
Artem Fedosov
  • 2,163
  • 2
  • 18
  • 28
  • This works, thanks! However days is going to be an integer so technically this is not accepting a function as its argument, isn't that what a decorator is supposed to do? Also why do you need two nested functions and not just one? – mesllo Aug 28 '15 at 09:37
  • 2
    @jablesauce please read the duplicate, which explains all of this. – jonrsharpe Aug 28 '15 at 09:39