Advertisement
Guest User

Untitled

a guest
Jan 24th, 2014
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.14 KB | None | 0 0
  1. _sentinel=object()
  2.  
  3. # like the tp_iter slot on new-style classes
  4. # http://hg.python.org/cpython/file/c6e529c1f87c/Objects/typeobject.c#l5907
  5. def _tp_iter(object):
  6.     typ = type(object)
  7.     __iter__ = getattr(typ, '__iter__', _sentinel)
  8.     if __iter__ is not _sentinel:
  9.         return __iter__()
  10.     __getitem__ = getattr(type, '__getitem__', _sentinel)
  11.     if __getitem__ is _sentinel:
  12.         raise TypeError("'%.200s' object is not iterable' % typ.__name__)
  13.    return SequenceIterator(object)
  14.  
  15. # like the PyObject_GetIter function
  16. # http://hg.python.org/cpython/file/c6e529c1f87c/Objects/abstract.c#l2644
  17. def _iter(object):
  18.    it = _tp_iter(object)
  19.    if not isinstance(it, Iterable):
  20.        raise TypeError("iter() returned non-iterator of type '%.100s'" % type(it).__name__)
  21.    return it
  22.  
  23. # like the actual tier function
  24. # http://hg.python.org/cpython/file/c6e529c1f87c/Python/bltinmodule.c#l1290
  25. def iter(object, sentinel=_sentinel):
  26.    if sentinel is _sentinel:
  27.        return _iter(object)
  28.    if not callable(object):
  29.        raise TypeError("iter(v, w): v must be callable")
  30.    return CallableIterator(object, sentinel)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement