Last active
December 6, 2017 11:03
-
-
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)
This file contains 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 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 |
This file contains 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
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