From 347634f5368f7dbae55eaa9770490ebb641fff2c Mon Sep 17 00:00:00 2001 From: gouravkr Date: Sun, 27 Feb 2022 19:26:03 +0530 Subject: [PATCH] date_parser decorator now only needs positions Implemented using inspector.signature --- fincal/core.py | 17 +++++++++++------ fincal/fincal.py | 4 ++-- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/fincal/core.py b/fincal/core.py index 1f94877..3f3ab7c 100644 --- a/fincal/core.py +++ b/fincal/core.py @@ -1,4 +1,5 @@ import datetime +import inspect from collections import UserDict, UserList from dataclasses import dataclass from numbers import Number @@ -16,23 +17,27 @@ class Frequency: symbol: str -def date_parser(pos, params): +def date_parser(pos): def parse_dates(func): def wrapper_func(*args, **kwargs): date_format = kwargs.get("date_format", None) args = list(args) - for i, j in enumerate(params): - date = kwargs.get(j, None) + sig = inspect.signature(func) + params = [i[0] for i in sig.parameters.items()] + # print(params) + for j in pos: + kwarg = params[j] + date = kwargs.get(kwarg, None) in_args = False if date is None: - date = args[pos[i]] + date = args[j] in_args = True parsed_date = _parse_date(date, date_format) if not in_args: - kwargs[j] = parsed_date + kwargs[kwarg] = parsed_date else: - args[pos[i]] = parsed_date + args[j] = parsed_date return func(*args, **kwargs) return wrapper_func diff --git a/fincal/fincal.py b/fincal/fincal.py index e3b994b..aa703cd 100644 --- a/fincal/fincal.py +++ b/fincal/fincal.py @@ -184,7 +184,7 @@ class TimeSeries(TimeSeriesCore): return self.__class__(new_ts, frequency=self.frequency.symbol) - @date_parser(pos=[1], params=['as_on']) + @date_parser(pos=[1]) def calculate_returns( self, as_on: Union[str, datetime.datetime], @@ -277,7 +277,7 @@ class TimeSeries(TimeSeriesCore): returns = returns ** (1 / years) return (current[0] if return_actual_date else as_on), returns - 1 - @date_parser(pos=[1, 2], params=['from_date', 'to_date']) + @date_parser(pos=[1, 2]) def calculate_rolling_returns( self, from_date: Union[datetime.date, str],