Created
May 20, 2017 07:49
-
-
Save Varriount/642802396582bee73c1065471d7b3e70 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
# Stringify an integer | |
stringified_int = Schema(All( | |
int, | |
Coerce(str) # Same as `lambda x: str(x) | |
)) | |
def AcceptSingleOrListOf(sub_schema): | |
""" | |
Returns a wrapped schema that either accepts the original schema, or a list | |
of values of the original schema. Transforms all values into a list of | |
the schema. | |
:param sub_schema: Schema to use. | |
:return: A wrapped schema. | |
""""" | |
return Any( | |
# List of sub_schema values | |
[sub_schema], | |
# 'All' is a pipeline. The original value is fed to the first filter, | |
# and inputs/outputs are chained along the list. | |
All(sub_schema, lambda x: [x]) | |
) | |
s = AcceptSingleOrListOf(stringified_int) | |
print(s(5)) # 5 | |
print(s([1,2,3]) # [1,2,3] | |
print(s(None)) # Throws exception | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment