tretool 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tretool/markfunc.py ADDED
@@ -0,0 +1,152 @@
1
+ """
2
+ ### 标记函数,并在调用时发出提示。
3
+ ##### 例:
4
+ ```
5
+ @wrapper.deprecated_func(version='1.2.1', alternative='main')
6
+ def slow():
7
+ print('slow func')
8
+ """
9
+
10
+ import functools
11
+ import warnings
12
+ import inspect
13
+ import time
14
+
15
+ from typing import Optional, Callable, Any
16
+
17
+
18
+ def info(func: Optional[Callable] = None, *,
19
+ show_args: bool = True,
20
+ show_kwargs: bool = True,
21
+ show_return: bool = True,
22
+ show_time: bool = True,
23
+ log_file: Optional[str] = None,
24
+ indent: int = 0) -> Callable:
25
+ """
26
+ 装饰器:输出函数的详细调用信息
27
+
28
+ 参数:
29
+ func (Callable): 被装饰的函数(自动传入,无需手动指定)
30
+ show_args (bool): 是否显示位置参数,默认True
31
+ show_kwargs (bool): 是否显示关键字参数,默认True
32
+ show_return (bool): 是否显示返回值,默认True
33
+ show_time (bool): 是否显示执行时间,默认True
34
+ log_file (str): 日志文件路径,不指定则输出到stdout
35
+ indent (int): 缩进空格数,用于嵌套调用时格式化输出
36
+
37
+ 返回:
38
+ 包装后的函数,调用时会输出详细信息
39
+
40
+ 示例:
41
+ ```python
42
+ @info()
43
+ def add(a, b):
44
+ return a + b
45
+
46
+ @info(show_kwargs=False, log_file="app.log")
47
+ def greet(name, message="Hello"):
48
+ return f"{message}, {name}"
49
+ ```
50
+ """
51
+ def decorator(f: Callable) -> Callable:
52
+ @functools.wraps(f)
53
+ def wrapper(*args, **kwargs) -> Any:
54
+ # 准备输出内容
55
+ output = []
56
+ indent_str = ' ' * indent
57
+
58
+ # 函数基本信息
59
+ output.append(f"{indent_str}┌── 调用函数: {f.__name__}")
60
+
61
+ # 参数信息
62
+ if show_args and args:
63
+ sig = inspect.signature(f)
64
+ params = list(sig.parameters.values())
65
+ arg_details = []
66
+ for i, arg in enumerate(args):
67
+ if i < len(params):
68
+ param_name = params[i].name
69
+ arg_details.append(f"{param_name}={repr(arg)}")
70
+ else:
71
+ arg_details.append(repr(arg))
72
+ output.append(f"{indent_str}├── 位置参数: {', '.join(arg_details)}")
73
+
74
+ if show_kwargs and kwargs:
75
+ kwargs_details = [f"{k}={repr(v)}" for k, v in kwargs.items()]
76
+ output.append(f"{indent_str}├── 关键字参数: {', '.join(kwargs_details)}")
77
+
78
+ # 执行函数并计时
79
+ start_time = time.perf_counter()
80
+ result = f(*args, **kwargs)
81
+ elapsed = time.perf_counter() - start_time
82
+
83
+ # 返回值和执行时间
84
+ if show_return:
85
+ output.append(f"{indent_str}├── 返回值: {repr(result)}")
86
+
87
+ if show_time:
88
+ output.append(f"{indent_str}└── 执行时间: {elapsed:.6f}秒")
89
+ else:
90
+ output[-1] = output[-1].replace('├──', '└──')
91
+
92
+ # 输出日志
93
+ log_message = '\n'.join(output)
94
+ if log_file:
95
+ with open(log_file, 'a', encoding='utf-8') as f:
96
+ f.write(log_message + '\n\n')
97
+ else:
98
+ print(log_message + '\n')
99
+
100
+ return result
101
+
102
+ return wrapper
103
+
104
+ # 处理带参数和不带参数的装饰器用法
105
+ if func is None:
106
+ return decorator
107
+ else:
108
+ return decorator(func)
109
+
110
+
111
+
112
+ def deprecated_func(original_func=None, *, reason=None, version=None, alternative=None):
113
+ """
114
+ 装饰器:标记函数已弃用,并在调用时发出警告
115
+
116
+ 参数:
117
+ reason (str): 弃用的原因说明
118
+ version (str): 计划移除的版本号
119
+ alternative (str): 推荐的替代函数或方法
120
+
121
+ 返回:
122
+ 包装后的函数,调用时会发出弃用警告
123
+
124
+ 示例:
125
+ ```@deprecated_func(reason="使用新API", version="2.0", alternative="new_function")
126
+ def old_function():
127
+ pass
128
+ """
129
+ def decorator(func):
130
+ @functools.wraps(func)
131
+ def wrapper(*args, **kwargs):
132
+ # 构建详细的警告消息
133
+ message = f"函数 {func.__name__} 已被弃用"
134
+ if reason:
135
+ message += f",原因: {reason}"
136
+ if version:
137
+ message += f",将在 {version} 版本中移除"
138
+ if alternative:
139
+ message += f",请使用 {alternative} 替代"
140
+
141
+ # 发出更正式的警告
142
+ warnings.warn(message, category=DeprecationWarning, stacklevel=2)
143
+
144
+ # 执行原始函数
145
+ return func(*args, **kwargs)
146
+ return wrapper
147
+
148
+ # 处理带参数和不带参数的装饰器用法
149
+ if original_func is None:
150
+ return decorator
151
+ else:
152
+ return decorator(original_func)