Advertisement
Guest User

Untitled

a guest
Apr 19th, 2014
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. def _append_or_set(x, to_append):
  2. if x is None:
  3. return to_append
  4. if type(x) is str:
  5. return [x, to_append]
  6. if type(x) is list:
  7. x.append(to_append)
  8. return x
  9.  
  10. def _filter_data(filter_by):
  11. filter_by = _append_or_set(filter_by, 'foo')
  12. return do_my_filtering(filter_by)
  13.  
  14. >>> def _append_or_set(x, to_append):
  15. ... try:
  16. ... x.append(to_append)
  17. ... except AttributeError:
  18. ... if x:
  19. ... x = [x, to_append]
  20. ... else:
  21. ... x = to_append
  22. ... finally:
  23. ... return x
  24. ...
  25. >>> _append_or_set([5,3,4], 6)
  26. [5, 3, 4, 6]
  27. >>> _append_or_set("this is x,", "this is appended")
  28. ['this is x,', 'this is appended']
  29. >>> _append_or_set(None, "hello")
  30. 'hello'
  31.  
  32. def _append_or_set(x, to_append):
  33. if x is None:
  34. return [to_append]
  35. elif isinstance(x, (list, tuple, set)): # also accept tuples and sets
  36. return list(x) + [to_append]
  37. else:
  38. # assume that anything else is fine as the first element
  39. return [x, to_append]
  40.  
  41. @singledispatch
  42. def append_or_set(x, to_append):
  43. raise RuntimeError("Unregistered type")
  44.  
  45. # This one isn't strictly necessary; you could just have the default behavior
  46. # in the original function be to return the value to append if no other types
  47. # will be supplied.
  48. @append_or_set.register(type(None))
  49. def append_or_set(x, to_append):
  50. return to_append
  51.  
  52.  
  53. @append_or_set.register(str)
  54. def append_or_set(x, to_append):
  55. return [x, to_append]
  56.  
  57. @append_or_set.register(list)
  58. def append_or_set(x, to_append):
  59. x.append(to_append)
  60. return x
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement