Skip to content

Instantly share code, notes, and snippets.

@Xowap
Last active December 6, 2017 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xowap/57bacfc2863e42ad7d48f2e69124f746 to your computer and use it in GitHub Desktop.
Save Xowap/57bacfc2863e42ad7d48f2e69124f746 to your computer and use it in GitHub Desktop.
An attempt to validate data as you read it (something in the mood of PEP 463)
from typing import TypeVar, Callable, Any, Optional, Tuple, Type
DATA_ERROR = (
KeyError,
TypeError,
ValueError,
AttributeError,
IndexError,
AssertionError,
)
D = TypeVar('D')
def d(
cb: Callable[[], D],
default: Optional[D] = None,
check_type: bool=True,
exception: Tuple[Type[Exception], ...] = DATA_ERROR,
) -> D:
try:
out = cb()
if check_type and default is not None:
assert isinstance(out, default.__class__)
return out
except exception:
return default
except AssertionError:
return default
data = {
'foo': [1, 2, 3],
'bar': 'fukyou',
}
print(d(lambda: data['foo'], []))
# [1, 2, 3]
print(d(lambda: data['bar'], []))
# []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment