Skip to content

Commit 580002c

Browse files
committed
add classattributes decorator
Signed-off-by: hwassman <[email protected]>
1 parent d365b1a commit 580002c

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

source/utils.py

Lines changed: 32 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,37 @@ 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+
def classattributes(default_attr,more_allowed_attr):
55+
""" class __init__decorator
56+
Parses kwargs attributes, for optional arguments uses default values,
57+
if not provided with kwargs
58+
Usage:
59+
1st arg is a dict of attributes with default values
60+
2nd arg is a list of additional allowed attributes which may be instantiated or not
61+
"""
62+
def class_decorator(cls):
63+
def new_init(self,**kwargs):
64+
allowed_attr = list(default_attr.keys()) + more_allowed_attr
65+
default_attr_to_update = copy.deepcopy(default_attr)
66+
default_attr_to_update.update(kwargs)
67+
self.__dict__.update((k,v) for k,v in default_attr_to_update.items() if k in allowed_attr)
68+
cls.__init__ = new_init
69+
return cls
70+
return class_decorator
71+
72+
def getTimeMultiplier(timeunit):
73+
'''Translate OpenTSDB time units, ignoring ms (milliseconds)'''
74+
return {
75+
's': 1,
76+
'm': 60,
77+
'h': 3600,
78+
'd': 86400,
79+
'w': 604800,
80+
'n': 2628000,
81+
'y': 31536000, }.get(timeunit, -1)

0 commit comments

Comments
 (0)