Last active
November 21, 2020 06:12
-
-
Save vitalizzare/1d338b8a67781ed9c861ac32ad51a987 to your computer and use it in GitHub Desktop.
A safe get by key function with the default parameter (decorators in python)
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
| from safe import safe | |
| def get(default=None): | |
| '''Return a function f(struct, key) to obtain the value | |
| struct[key] or default if key is out of range. | |
| ''' | |
| return safe(default)(lambda struct, key: struct[key]) |
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
| '''Test the get function''' | |
| from get import get | |
| struct = [10, 20, 30] | |
| key = len(struct) + 1 | |
| default = 'BLOB' | |
| print('Testing of the safe get function.') | |
| print('struct =', repr(struct)) | |
| print('invalid key is', key) | |
| print('defaul =', repr(default)) | |
| print('struct[key] =', repr(get(default)(struct, key))) | |
| try: | |
| assert get(default)(struct, key) == default | |
| except AssertionError: | |
| print('ERROR: got {!r} while expected {!r}'.format( | |
| get(default)(struct, key), default)) | |
| else: | |
| print('Test passed: the expected default value is obtained.') |
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
| def safe(default=None): | |
| '''Decorator to handle runtime errors | |
| Return the default value when an error occurred''' | |
| def proxy(func): | |
| from functools import wraps | |
| @wraps(func) | |
| def wrapped(*args, **kwargs): | |
| try: | |
| return func(*args, **kwargs) | |
| except Exception: | |
| return default | |
| return wrapped | |
| return proxy | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment