Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def _append_or_set(x, to_append):
- if x is None:
- return to_append
- if type(x) is str:
- return [x, to_append]
- if type(x) is list:
- x.append(to_append)
- return x
- def _filter_data(filter_by):
- filter_by = _append_or_set(filter_by, 'foo')
- return do_my_filtering(filter_by)
- >>> def _append_or_set(x, to_append):
- ... try:
- ... x.append(to_append)
- ... except AttributeError:
- ... if x:
- ... x = [x, to_append]
- ... else:
- ... x = to_append
- ... finally:
- ... return x
- ...
- >>> _append_or_set([5,3,4], 6)
- [5, 3, 4, 6]
- >>> _append_or_set("this is x,", "this is appended")
- ['this is x,', 'this is appended']
- >>> _append_or_set(None, "hello")
- 'hello'
- def _append_or_set(x, to_append):
- if x is None:
- return [to_append]
- elif isinstance(x, (list, tuple, set)): # also accept tuples and sets
- return list(x) + [to_append]
- else:
- # assume that anything else is fine as the first element
- return [x, to_append]
- @singledispatch
- def append_or_set(x, to_append):
- raise RuntimeError("Unregistered type")
- # This one isn't strictly necessary; you could just have the default behavior
- # in the original function be to return the value to append if no other types
- # will be supplied.
- @append_or_set.register(type(None))
- def append_or_set(x, to_append):
- return to_append
- @append_or_set.register(str)
- def append_or_set(x, to_append):
- return [x, to_append]
- @append_or_set.register(list)
- def append_or_set(x, to_append):
- x.append(to_append)
- return x
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement