Skip to content

Instantly share code, notes, and snippets.

@RyanJulyan
Last active December 9, 2023 06:51
Show Gist options
  • Save RyanJulyan/ecab13388535d86ca745337975899312 to your computer and use it in GitHub Desktop.
Save RyanJulyan/ecab13388535d86ca745337975899312 to your computer and use it in GitHub Desktop.
Python decorator with control points to validate data before processing. It features an abstract base class for defining controls and subclasses for specific checks, such as positive and even value verification. The decorator is applied to a function, ensuring data meets criteria before processing.
from typing import Callable, List
def control_point_decorator(control_points: List['BaseControl']) -> Callable:
"""
Decorator function to apply control point checks before executing a function.
Args:
control_points (List[BaseControl]): A list of control point objects which will be used to check the data
before passing it to the decorated function.
Returns:
Callable: A wrapper function that incorporates control point checks before executing the decorated function.
"""
def decorator(func):
def wrapper(*args, **kwargs):
for control_point in control_points:
if not control_point.check(args[0]):
print(f"Control '{control_point.name}' failed. Stopping execution.")
return None
result = func(*args, **kwargs)
return result
return wrapper
return decorator
# Could be an interface/ABC
class BaseControl:
"""
Base class for control points.
Subclasses must implement the check method.
"""
def __init__(self, name):
self.name = name
def check(self, data):
raise NotImplementedError("Subclasses should implement this method.")
if __name__ == "__main__":
# This could become a lib, but imagine it would be specific to te client?
class PositiveValueControl(BaseControl):
"""
Control point to check if a value is positive.
"""
def check(self, data):
return data > 0
class EvenValueControl(BaseControl):
"""
Control point to check if a value is even.
"""
def check(self, data):
return data % 2 == 0
# This would be in client implementation files
control_points = [
PositiveValueControl("Positive Value Check"),
EvenValueControl("Even Value Check"),
]
@control_point_decorator(control_points)
def process_data(data):
"""
Process the data if it passes all control checks.
Args:
data (int): The data to be processed.
Returns:
Optional[int]: The processed data or None if control checks fail.
"""
# Continue processing the data
print("All controls passed. Processing the data.")
return data * 2
print()
print("Test 1 pass:")
data = 42
result = process_data(data)
print("Result:", result)
print()
print("Test 2 fail:")
data = 43
result = process_data(data)
print("Result:", result)
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment