decorator.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. # This Python file uses the following encoding: utf-8
  2. from functools import wraps
  3. from typing import Callable, Generic, TypeVar
  4. T = TypeVar("T")
  5. class Config:
  6. """
  7. Decorator that calls different function with a same name according to config.
  8. func_list likes:
  9. func_list = {
  10. 'func1': [
  11. {'options': {'ENABLE': True}, 'func': 1},
  12. {'options': {'ENABLE': False}, 'func': 1}
  13. ]
  14. }
  15. """
  16. func_list = {}
  17. """
  18. 这段代码定义了一个名为`Config`的类,其中包含一个名为`when`的装饰器方法。该装饰器用于根据配置的不同,在调用具有相同名称的函数时选择不同的函数。
  19. 在`Config`类中,有一个类变量`func_list`,用于存储函数的配置和对应的函数。`func_list`的结构是一个字典,其中键是函数的名称,值是一个列表,列表中的每个元素是一个字典,包含了选项和对应的函数。每个选项是一个字典,表示配置选项及其值,函数是一个可调用对象。
  20. `when`装饰器的作用是将装饰的函数添加到`func_list`中。装饰器接受一个或多个关键字参数,这些参数是AzurLaneConfig中的选项。装饰器内部定义了一个`decorate`函数作为装饰器的实际实现。
  21. 在`decorate`函数内部,首先获取被装饰函数的名称和选项,并将它们保存在一个字典中。然后判断该函数名称是否已经存在于`func_list`中,如果不存在,则将该函数及其选项添加到`func_list`中;如果存在,则检查是否有相同选项的记录,如果有,则覆盖原有的函数;如果没有,则添加新的记录。
  22. 接下来,使用`@wraps(func)`装饰器来保留原始函数的元数据。然后定义了一个名为`wrapper`的内部函数作为装饰后的函数。在`wrapper`函数内部,遍历函数名称在`func_list`中的记录,对于每个记录,检查选项是否匹配当前的配置。如果匹配,则调用对应的函数并返回结果;如果没有匹配的选项,则使用最后定义的函数作为默认函数,并打印警告信息。最后,返回`wrapper`函数作为装饰后的函数。
  23. 通过使用`@Config.when()`语法将装饰器应用于函数,可以根据不同的配置选项选择不同的函数执行。
  24. """
  25. @classmethod
  26. def when(cls, **kwargs):
  27. """
  28. Args:
  29. **kwargs: Any option in AzurLaneConfig.
  30. Examples:
  31. @Config.when(USE_ONE_CLICK_RETIREMENT=True)
  32. def retire_ships(self, amount=None, rarity=None):
  33. pass
  34. @Config.when(USE_ONE_CLICK_RETIREMENT=False)
  35. def retire_ships(self, amount=None, rarity=None):
  36. pass
  37. """
  38. from module.logger import logger
  39. options = kwargs
  40. def decorate(func):
  41. name = func.__name__
  42. data = {'options': options, 'func': func}
  43. if name not in cls.func_list:
  44. cls.func_list[name] = [data]
  45. else:
  46. override = False
  47. for record in cls.func_list[name]:
  48. if record['options'] == data['options']:
  49. record['func'] = data['func']
  50. override = True
  51. if not override:
  52. cls.func_list[name].append(data)
  53. @wraps(func)
  54. def wrapper(self, *args, **kwargs):
  55. """
  56. Args:
  57. self: ModuleBase instance.
  58. *args:
  59. **kwargs:
  60. """
  61. for record in cls.func_list[name]:
  62. flag = [value is None or self.config.__getattribute__(key) == value
  63. for key, value in record['options'].items()]
  64. if not all(flag):
  65. continue
  66. return record['func'](self, *args, **kwargs)
  67. logger.warning(f'No option fits for {name}, using the last define func.')
  68. return func(self, *args, **kwargs)
  69. return wrapper
  70. return decorate
  71. class cached_property(Generic[T]):
  72. """
  73. cached-property from https://github.com/pydanny/cached-property
  74. Add typing support
  75. A property that is only computed once per instance and then replaces itself
  76. with an ordinary attribute. Deleting the attribute resets the property.
  77. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76
  78. """
  79. def __init__(self, func: Callable[..., T]):
  80. self.func = func
  81. def __get__(self, obj, cls) -> T:
  82. if obj is None:
  83. return self
  84. value = obj.__dict__[self.func.__name__] = self.func(obj)
  85. return value
  86. def del_cached_property(obj, name):
  87. """
  88. Delete a cached property safely.
  89. Args:
  90. obj:
  91. name (str):
  92. """
  93. try:
  94. del obj.__dict__[name]
  95. except KeyError:
  96. pass
  97. def has_cached_property(obj, name):
  98. """
  99. Check if a property is cached.
  100. Args:
  101. obj:
  102. name (str):
  103. """
  104. return name in obj.__dict__
  105. def function_drop(rate=0.5, default=None):
  106. """
  107. Drop function calls to simulate random emulator stuck, for testing purpose.
  108. Args:
  109. rate (float): 0 to 1. Drop rate.
  110. default: Default value to return if dropped.
  111. Examples:
  112. @function_drop(0.3)
  113. def click(self, button, record_check=True):
  114. pass
  115. 30% possibility:
  116. INFO | Dropped: module.device.device.Device.click(REWARD_GOTO_MAIN, record_check=True)
  117. 70% possibility:
  118. INFO | Click (1091, 628) @ REWARD_GOTO_MAIN
  119. """
  120. from module.logger import logger
  121. def decorate(func):
  122. @wraps(func)
  123. def wrapper(*args, **kwargs):
  124. if random.uniform(0, 1) > rate:
  125. return func(*args, **kwargs)
  126. else:
  127. cls = ''
  128. arguments = [str(arg) for arg in args]
  129. if len(arguments):
  130. matched = re.search('<(.*?) object at', arguments[0])
  131. if matched:
  132. cls = matched.group(1) + '.'
  133. arguments.pop(0)
  134. arguments += [f'{k}={v}' for k, v in kwargs.items()]
  135. arguments = ', '.join(arguments)
  136. logger.info(f'Dropped: {cls}{func.__name__}({arguments})')
  137. return default
  138. return wrapper
  139. return decorate
  140. def run_once(f):
  141. """
  142. Run a function only once, no matter how many times it has been called.
  143. Examples:
  144. @run_once
  145. def my_function(foo, bar):
  146. return foo + bar
  147. while 1:
  148. my_function()
  149. Examples:
  150. def my_function(foo, bar):
  151. return foo + bar
  152. action = run_once(my_function)
  153. while 1:
  154. action()
  155. """
  156. @wraps(f)
  157. def wrapper(*args, **kwargs):
  158. if not wrapper.has_run:
  159. wrapper.has_run = True
  160. return f(*args, **kwargs)
  161. wrapper.has_run = False
  162. return wrapper