Skip to content

Commit 1ec233a

Browse files
authored
Merge pull request #121 from Helene/classattributes
Add helpful decorator methods
2 parents d365b1a + 833f520 commit 1ec233a

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

source/utils.py

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
'''
2222

2323
import time
24+
import copy
2425
from typing import Callable, TypeVar, Any
2526
from functools import wraps
2627
from messages import MSG
@@ -44,8 +45,32 @@ def wrapper(*args: Any, **kwargs: Any) -> T:
4445
duration = time.time() - t
4546
if not skip_attribute:
4647
wrapper._execution_duration = duration # type: ignore
47-
self.logger.trace(MSG['RunMethod'].format(f.__name__, ', '.join(filter(None, [args_str, kwargs_str]))))
48-
self.logger.trace(MSG['TimerInfo'].format(f.__name__, duration))
48+
self.logger.debug(MSG['RunMethod'].format(f.__name__, ', '.join(filter(None, [args_str, kwargs_str]))))
49+
self.logger.debug(MSG['TimerInfo'].format(f.__name__, duration))
4950
return result
5051
return wrapper
5152
return outer
53+
54+
55+
def classattributes(default_attr: dict, more_allowed_attr: list):
56+
""" class __init__decorator
57+
Parses kwargs attributes, for optional arguments uses default values,
58+
if not provided with kwargs
59+
Usage:
60+
1st arg is a dict of attributes with default values
61+
2nd arg is a list of additional allowed attributes which may be instantiated or not
62+
"""
63+
def class_decorator(cls):
64+
def new_init(self, **kwargs):
65+
allowed_attr = list(default_attr.keys()) + more_allowed_attr
66+
default_attr_to_update = copy.deepcopy(default_attr)
67+
default_attr_to_update.update(kwargs)
68+
self.__dict__.update((k, v) for k, v in default_attr_to_update.items() if k in allowed_attr)
69+
cls.__init__ = new_init
70+
return cls
71+
return class_decorator
72+
73+
74+
def getTimeMultiplier(timeunit):
75+
""" Translate OpenTSDB time units, ignoring ms (milliseconds) """
76+
return {'s': 1, 'm': 60, 'h': 3600, 'd': 86400, 'w': 604800, 'n': 2628000, 'y': 31536000}.get(timeunit, -1)

0 commit comments

Comments
 (0)