Skip to content

Instantly share code, notes, and snippets.

@vitalizzare
Last active November 21, 2020 06:12
Show Gist options
  • Select an option

  • Save vitalizzare/1d338b8a67781ed9c861ac32ad51a987 to your computer and use it in GitHub Desktop.

Select an option

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)
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])
'''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.')
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