Skip to content

Commit

Permalink
Enhance iterlen() and add doctest to Bio/_utils.py
Browse files Browse the repository at this point in the history
  • Loading branch information
peterjc committed Jan 10, 2013
1 parent 20ddedf commit 57ae89c
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions Bio/_utils.py
Expand Up @@ -12,11 +12,27 @@
def iterlen(items): def iterlen(items):
"""Count the number of items in an iterable. """Count the number of items in an iterable.
If the argument supports len(items), and some iterators do, then
this returns len(items). Otherwise it will scan over the entries
in order to count them.
Exhausts a generator, but doesn't require creating a full list. Exhausts a generator, but doesn't require creating a full list.
>>> iterlen("abcde")
5
>>> iterlen(iter("abcde"))
5
>>> iterlen(xrange(5))
5
""" """
for i, x in enumerate(items): try:
count = i #e.g. Under Python 2, the xrange iterator defines __len__
return count + 1 return len(items)
except TypeError:
for i, x in enumerate(items):
count = i
return count + 1




def read_forward(handle): def read_forward(handle):
Expand Down Expand Up @@ -101,3 +117,6 @@ def run_doctest(target_dir=None, *args, **kwargs):
# and revert back to initial directory # and revert back to initial directory
os.chdir(cur_dir) os.chdir(cur_dir)
print "Done" print "Done"

if __name__ == "__main__":
run_doctest()

0 comments on commit 57ae89c

Please sign in to comment.