Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import funcy as fn
- def as_type(desired, *converters):
- """
- Return a type converter to `desired` type. `converters` are callables that can accept an object and try an convert it
- to desired type. If a converter may fail with any exception other than `TypeError` it should be given as a
- (callable, Exception) tuple.
- e.g.:
- as_date = as_type(date, date_parser, (lambda d: d.date(), AttributeError))
- d1 = as_date(date(2015, 11, 1)
- d2 = as_date('2015-11-1')
- d3 = as_date(datetime(2015, 11, 1, 0, 2, 1))
- assert d1 == d2 == d3
- """
- converters = [(converter, TypeError) if callable(converter) else converter]
- def converter(obj):
- if isinstance(obj, desired):
- return obj
- else:
- approaches = [(fn.partial(approach, obj), exception) for approach, exception in converters]
- return fn.fallback(approaches)
- return converter
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement