Skip to content

Commit dc63fc8

Browse files
committed
Add decorate to prevent an inner callable to run given a predicate
1 parent 362f33a commit dc63fc8

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/clabe/launcher/_callable_manager.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,3 +194,30 @@ def wrapper(*args, **kwargs):
194194
return wrapper
195195

196196
return decorator
197+
198+
199+
def run_if(predicate: t.Callable[..., bool]) -> t.Callable[[t.Callable[P, R]], t.Callable[P, Optional[R]]]:
200+
"""
201+
A decorator that only runs the wrapped function if the predicate returns True.
202+
If the predicate returns False, returns None.
203+
204+
Args:
205+
predicate: A callable that takes the same arguments as the wrapped function and returns a boolean.
206+
207+
Returns:
208+
The decorated function that runs only if predicate(*args, **kwargs) is True, else returns None.
209+
"""
210+
211+
def decorator(func: t.Callable[P, R]) -> t.Callable[P, Optional[R]]:
212+
@functools.wraps(func)
213+
def wrapper(*args, **kwargs):
214+
fn_name = getattr(func, "__name__", repr(func))
215+
if predicate(*args, **kwargs):
216+
logger.debug(f"Predicate passed for {fn_name}, executing function")
217+
return func(*args, **kwargs)
218+
logger.debug(f"Predicate failed for {fn_name}, skipping execution")
219+
return None
220+
221+
return wrapper
222+
223+
return decorator

0 commit comments

Comments
 (0)