python - How to check if an iterable can be traversed again? -
consider following code:
def my_fun(an_iterable): val in an_iterable: do_work(val) if some_cond(val): do_some_other_work(an_iterable) break if an_iterable list/tuple, do_some_other_work whole list again. if an_iterable iterator or generator, receive rest of items in list. how differentiate between 2 cases? want do_some_other_work receive rest of items only.
there's no general way tell whether can iterate on object repeatedly. file-like objects, in particular, screw checks. fortunately, don't need check this. if want make sure do_some_other_work gets rest of items, can explicitly request iterator:
def my_fun(iterable): iterable = iter(iterable) # whatever.
Comments
Post a Comment