Advertisement
Guest User

Untitled

a guest
Dec 1st, 2015
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. import funcy as fn
  2.  
  3.  
  4. def as_type(desired, *converters):
  5. """
  6. Return a type converter to `desired` type. `converters` are callables that can accept an object and try an convert it
  7. to desired type. If a converter may fail with any exception other than `TypeError` it should be given as a
  8. (callable, Exception) tuple.
  9.  
  10. e.g.:
  11. as_date = as_type(date, date_parser, (lambda d: d.date(), AttributeError))
  12. d1 = as_date(date(2015, 11, 1)
  13. d2 = as_date('2015-11-1')
  14. d3 = as_date(datetime(2015, 11, 1, 0, 2, 1))
  15. assert d1 == d2 == d3
  16. """
  17. converters = [(converter, TypeError) if callable(converter) else converter]
  18. def converter(obj):
  19. if isinstance(obj, desired):
  20. return obj
  21. else:
  22. approaches = [(fn.partial(approach, obj), exception) for approach, exception in converters]
  23. return fn.fallback(approaches)
  24. return converter
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement