Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Enhance iterlen() and add doctest to Bio/_utils.py

  • Loading branch information...
commit 57ae89cdedbc1e18495ffb615a3a1d2c9feb0296 1 parent 20ddedf
@peterjc peterjc authored
Showing with 22 additions and 3 deletions.
  1. +22 −3 Bio/_utils.py
View
25 Bio/_utils.py
@@ -12,11 +12,27 @@
def iterlen(items):
"""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.
+
+ >>> iterlen("abcde")
+ 5
+ >>> iterlen(iter("abcde"))
+ 5
+ >>> iterlen(xrange(5))
+ 5
+
"""
- for i, x in enumerate(items):
- count = i
- return count + 1
+ try:
+ #e.g. Under Python 2, the xrange iterator defines __len__
+ return len(items)
+ except TypeError:
+ for i, x in enumerate(items):
+ count = i
+ return count + 1
def read_forward(handle):
@@ -101,3 +117,6 @@ def run_doctest(target_dir=None, *args, **kwargs):
# and revert back to initial directory
os.chdir(cur_dir)
print "Done"
+
+if __name__ == "__main__":
+ run_doctest()
Please sign in to comment.
Something went wrong with that request. Please try again.