Created
June 14, 2010 17:49
-
-
Save lqc/438009 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import functools | |
| import datetime | |
| def with_time(func): | |
| @functools.wraps(func) | |
| def timed_execution(*args, **kwargs): | |
| start = datetime.datetime.now() | |
| try: | |
| result = func(*args, **kwargs) | |
| time = datetime.datetime.now() - start | |
| return time, result | |
| except Exception as e: | |
| return None, e | |
| return timed_execution | |
| class InvalidResult(Exception): | |
| pass | |
| def valid_with_time(validator=None): | |
| def decorator(func): | |
| timed_execution = with_time(func) | |
| @functools.wraps(func) | |
| def valid_execution(*args, **kwargs): | |
| time, result = timed_execution(*args, **kwargs) | |
| try: | |
| if time is not None: | |
| validator(result) | |
| return time, result | |
| except InvalidResult as e: | |
| return None, e | |
| return valid_execution | |
| return decorator | |
| @with_time | |
| def add_five(n): | |
| return n + 5 | |
| def check_small(x): | |
| if x > 100: | |
| raise InvalidResult("Number too large") | |
| @valid_with_time(validator=check_small) | |
| def add_numbers(a, b): | |
| return a + b | |
| print add_five(37) | |
| print add_numbers(20, 40) | |
| print add_numbers(100, 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment