Advertisement
Guest User

Untitled

a guest
Jan 24th, 2014
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.     __next__ = getattr(typ, '__next__', _sentinel)
  11.     if __next__ is not _sentinel:
  12.         return object
  13.     __getitem__ = getattr(type, '__getitem__', _sentinel)
  14.     if __getitem__ is _sentinel:
  15.         raise TypeError("'%.200s' object is not iterable' % typ.__name__)
  16.    return SequenceIterator(object)
  17.  
  18. # like the PyObject_GetIter function
  19. # http://hg.python.org/cpython/file/c6e529c1f87c/Objects/abstract.c#l2644
  20. def _iter(object):
  21.    it = _tp_iter(object)
  22.    if not isinstance(it, Iterable):
  23.        raise TypeError("iter() returned non-iterator of type '%.100s'" % type(it).__name__)
  24.    return it
  25.  
  26. # like the actual tier function
  27. # http://hg.python.org/cpython/file/c6e529c1f87c/Python/bltinmodule.c#l1290
  28. def iter(object, sentinel=_sentinel):
  29.    if sentinel is _sentinel:
  30.        return _iter(object)
  31.    if not callable(object):
  32.        raise TypeError("iter(v, w): v must be callable")
  33.    return CallableIterator(object, sentinel)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement