decorator-toolkit 0.1.0__tar.gz
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.
- decorator_toolkit-0.1.0/LICENSE +21 -0
- decorator_toolkit-0.1.0/PKG-INFO +8 -0
- decorator_toolkit-0.1.0/README.md +16 -0
- decorator_toolkit-0.1.0/decorator_toolkit/__init__.py +10 -0
- decorator_toolkit-0.1.0/decorator_toolkit/decorator_tools.py +205 -0
- decorator_toolkit-0.1.0/decorator_toolkit/decorator_tools.pyi +9 -0
- decorator_toolkit-0.1.0/decorator_toolkit/py.typed +0 -0
- decorator_toolkit-0.1.0/decorator_toolkit.egg-info/PKG-INFO +8 -0
- decorator_toolkit-0.1.0/decorator_toolkit.egg-info/SOURCES.txt +11 -0
- decorator_toolkit-0.1.0/decorator_toolkit.egg-info/dependency_links.txt +1 -0
- decorator_toolkit-0.1.0/decorator_toolkit.egg-info/top_level.txt +1 -0
- decorator_toolkit-0.1.0/pyproject.toml +11 -0
- decorator_toolkit-0.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Adam Worsnip
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# decorator-toolkit
|
|
2
|
+
|
|
3
|
+
Type-safe Python decorators for logging, timing, memoization, and input validation.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
pip install decorator-toolkit
|
|
7
|
+
|
|
8
|
+
## Quick example
|
|
9
|
+
```py
|
|
10
|
+
from decorator_toolkit import log, timeit
|
|
11
|
+
|
|
12
|
+
@log("Multiplied a number by two.")
|
|
13
|
+
@timeit
|
|
14
|
+
def times_two(x: int) -> int:
|
|
15
|
+
return x * 2
|
|
16
|
+
```
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Decorator tools."""
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import logging
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from typing import TypeVar, ParamSpec, Callable
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
P = ParamSpec("P")
|
|
10
|
+
R = TypeVar("R")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def log(msg: str | None = None, success_msg: str | None = None, failed_msg: str | None = None) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
|
14
|
+
"""Log the execution of a function.
|
|
15
|
+
|
|
16
|
+
The decorator logs an optional base message when the function is called.
|
|
17
|
+
If the wrapped function returns a truthy value, `success_msg` is logged.
|
|
18
|
+
If it returns a falsy value, `failed_msg` is logged.
|
|
19
|
+
|
|
20
|
+
Messages are only logged if provided. Exceptions raised by the wrapped
|
|
21
|
+
function are not suppressed.
|
|
22
|
+
|
|
23
|
+
Parameters
|
|
24
|
+
----------
|
|
25
|
+
msg : str | None
|
|
26
|
+
Message logged every time the function is called.
|
|
27
|
+
success_msg : str | None
|
|
28
|
+
Message logged when the wrapped function returns a truthy value.
|
|
29
|
+
failed_msg : str | None
|
|
30
|
+
Message logged when the wrapped function returns a falsy value.
|
|
31
|
+
|
|
32
|
+
Example
|
|
33
|
+
-------
|
|
34
|
+
>>> import logging
|
|
35
|
+
>>> logging.basicConfig(level=logging.INFO)
|
|
36
|
+
>>>
|
|
37
|
+
>>> @log(msg="Running check", success_msg="Passed", failed_msg="Failed")
|
|
38
|
+
... def is_even(x: int) -> bool:
|
|
39
|
+
... return x % 2 == 0
|
|
40
|
+
>>>
|
|
41
|
+
>>> is_even(4)
|
|
42
|
+
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def decorator(func: Callable[P, R]) -> Callable[P, R]:
|
|
46
|
+
logger = logging.getLogger(func.__module__)
|
|
47
|
+
@functools.wraps(func)
|
|
48
|
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
|
49
|
+
logger.debug(f"Called {func.__name__} with args={args} & kwargs={kwargs}")
|
|
50
|
+
result = func(*args, **kwargs)
|
|
51
|
+
logger.debug(f"{func.__name__} returned {result} ({type(result)})")
|
|
52
|
+
if msg is not None:
|
|
53
|
+
logger.info(msg)
|
|
54
|
+
if isinstance(result, bool):
|
|
55
|
+
if result and success_msg:
|
|
56
|
+
logger.info(success_msg)
|
|
57
|
+
elif not result and failed_msg:
|
|
58
|
+
logger.info(failed_msg)
|
|
59
|
+
return result
|
|
60
|
+
|
|
61
|
+
return wrapper
|
|
62
|
+
|
|
63
|
+
return decorator
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def timeit(func: Callable[P, R]) -> Callable[P, R]:
|
|
67
|
+
"""Measure execution time of a function.
|
|
68
|
+
|
|
69
|
+
The decorator records how long the wrapped function takes to execute
|
|
70
|
+
and reports the duration. The original return value of the function
|
|
71
|
+
is preserved.
|
|
72
|
+
|
|
73
|
+
The timing mechanism measures total runtime from function entry to exit.
|
|
74
|
+
Exceptions raised by the wrapped function are not suppressed.
|
|
75
|
+
|
|
76
|
+
Parameters
|
|
77
|
+
----------
|
|
78
|
+
func : Callable[P, R]
|
|
79
|
+
The function whose execution time will be measured.
|
|
80
|
+
|
|
81
|
+
Returns
|
|
82
|
+
-------
|
|
83
|
+
Callable[P, R]
|
|
84
|
+
A wrapped function with identical signature and return value.
|
|
85
|
+
|
|
86
|
+
Example
|
|
87
|
+
-------
|
|
88
|
+
>>> @timeit
|
|
89
|
+
... def slow_operation() -> None:
|
|
90
|
+
... import time
|
|
91
|
+
... time.sleep(1)
|
|
92
|
+
...
|
|
93
|
+
>>> slow_operation()
|
|
94
|
+
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
@functools.wraps(func)
|
|
98
|
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
|
99
|
+
start = datetime.now()
|
|
100
|
+
result = func(*args, **kwargs)
|
|
101
|
+
time_taken = datetime.now() - start
|
|
102
|
+
milliseconds = time_taken.total_seconds() * 1000
|
|
103
|
+
print(f"'{func.__name__}' took {round(milliseconds, 2)} milliseconds to run.")
|
|
104
|
+
return result
|
|
105
|
+
|
|
106
|
+
return wrapper
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def memoize(func: Callable[P, R]) -> Callable[P, R]:
|
|
110
|
+
"""Cache function results based on input arguments.
|
|
111
|
+
|
|
112
|
+
The decorator stores results from previous calls and returns the cached
|
|
113
|
+
value when the function is called again with the same arguments.
|
|
114
|
+
This avoids repeated computation for identical inputs.
|
|
115
|
+
|
|
116
|
+
Cached values persist for the lifetime of the program unless explicitly
|
|
117
|
+
cleared by the implementation.
|
|
118
|
+
|
|
119
|
+
Parameters
|
|
120
|
+
----------
|
|
121
|
+
func : Callable[P, R]
|
|
122
|
+
The function whose results will be cached.
|
|
123
|
+
|
|
124
|
+
Returns
|
|
125
|
+
-------
|
|
126
|
+
Callable[P, R]
|
|
127
|
+
A wrapped function with identical signature and return value.
|
|
128
|
+
|
|
129
|
+
Example
|
|
130
|
+
-------
|
|
131
|
+
>>> @memoize
|
|
132
|
+
... def fibonacci(n: int) -> int:
|
|
133
|
+
... if n < 2:
|
|
134
|
+
... return n
|
|
135
|
+
... return fibonacci(n - 1) + fibonacci(n - 2)
|
|
136
|
+
...
|
|
137
|
+
>>> fibonacci(30)
|
|
138
|
+
|
|
139
|
+
"""
|
|
140
|
+
cache: dict[tuple[tuple[object, ...], frozenset[tuple[str, object]]], R] = {}
|
|
141
|
+
|
|
142
|
+
@functools.wraps(func)
|
|
143
|
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
|
144
|
+
key = (args, frozenset(kwargs.items()))
|
|
145
|
+
if key in cache:
|
|
146
|
+
return cache[key]
|
|
147
|
+
|
|
148
|
+
result = func(*args, **kwargs)
|
|
149
|
+
cache[key] = result
|
|
150
|
+
return result
|
|
151
|
+
|
|
152
|
+
return wrapper
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def validate(
|
|
156
|
+
condition: Callable[..., bool],
|
|
157
|
+
) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
|
158
|
+
"""Enforce a validation condition before function execution.
|
|
159
|
+
|
|
160
|
+
The decorator factory accepts a condition function that is evaluated
|
|
161
|
+
using the same arguments passed to the wrapped function. If the condition
|
|
162
|
+
evaluates to True, the function executes normally. If it evaluates to
|
|
163
|
+
False, execution is prevented and an exception is raised.
|
|
164
|
+
|
|
165
|
+
The wrapped function’s signature and return value are preserved.
|
|
166
|
+
|
|
167
|
+
Parameters
|
|
168
|
+
----------
|
|
169
|
+
condition : Callable[..., bool]
|
|
170
|
+
A callable that receives the same arguments as the wrapped function
|
|
171
|
+
and returns True if execution is allowed, or False otherwise.
|
|
172
|
+
|
|
173
|
+
Returns
|
|
174
|
+
-------
|
|
175
|
+
Callable[[Callable[P, R]], Callable[P, R]]
|
|
176
|
+
A decorator that applies the validation check.
|
|
177
|
+
|
|
178
|
+
Example
|
|
179
|
+
-------
|
|
180
|
+
>>> def not_negative(x: float) -> bool:
|
|
181
|
+
... if x >= 0:
|
|
182
|
+
... return True
|
|
183
|
+
... else:
|
|
184
|
+
... return False
|
|
185
|
+
...
|
|
186
|
+
>>> @validate(not_negative)
|
|
187
|
+
... def sqrt(x: float) -> float:
|
|
188
|
+
... return x ** 0.5
|
|
189
|
+
...
|
|
190
|
+
>>> sqrt(9)
|
|
191
|
+
>>> sqrt(-1) # validation fails
|
|
192
|
+
|
|
193
|
+
"""
|
|
194
|
+
|
|
195
|
+
def decorator(func: Callable[P, R]) -> Callable[P, R]:
|
|
196
|
+
@functools.wraps(func)
|
|
197
|
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
|
198
|
+
if not condition(*args, **kwargs):
|
|
199
|
+
logging.error("Validation failed.")
|
|
200
|
+
raise ValueError("Validation failed")
|
|
201
|
+
return func(*args, **kwargs)
|
|
202
|
+
|
|
203
|
+
return wrapper
|
|
204
|
+
|
|
205
|
+
return decorator
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
from typing import Callable, TypeVar, ParamSpec
|
|
2
|
+
|
|
3
|
+
P = ParamSpec("P")
|
|
4
|
+
R = TypeVar("R")
|
|
5
|
+
|
|
6
|
+
def log(msg: str | None = None, success_msg: str | None = None, failed_msg: str | None = None) -> Callable[[Callable[P, R]], Callable[P, R]]: ...
|
|
7
|
+
def timeit(func: Callable[P, R]) -> Callable[P, R]: ...
|
|
8
|
+
def memoize(func: Callable[P, R]) -> Callable[P, R]: ...
|
|
9
|
+
def validate(condition: Callable[..., bool],) -> Callable[[Callable[P, R]], Callable[P, R]]: ...
|
|
File without changes
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
decorator_toolkit/__init__.py
|
|
5
|
+
decorator_toolkit/decorator_tools.py
|
|
6
|
+
decorator_toolkit/decorator_tools.pyi
|
|
7
|
+
decorator_toolkit/py.typed
|
|
8
|
+
decorator_toolkit.egg-info/PKG-INFO
|
|
9
|
+
decorator_toolkit.egg-info/SOURCES.txt
|
|
10
|
+
decorator_toolkit.egg-info/dependency_links.txt
|
|
11
|
+
decorator_toolkit.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
decorator_toolkit
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "decorator_toolkit"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Type-safe decorators for logging, timing, retry, memoization, and validation."
|
|
5
|
+
authors = [{name = "Adam Worsnip"}]
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
dependencies = []
|
|
8
|
+
|
|
9
|
+
[build-system]
|
|
10
|
+
requires = ["setuptools", "wheel"]
|
|
11
|
+
build-backend = "setuptools.build_meta"
|