OpenQuizz
Une application de gestion des contenus pédagogiques
peekable Class Reference

Public Member Functions

def __init__ (self, iterable)
 
def __iter__ (self)
 
def __bool__ (self)
 
def peek (self, default=_marker)
 
def prepend (self, *items)
 
def __next__ (self)
 
def __getitem__ (self, index)
 

Detailed Description

Wrap an iterator to allow lookahead and prepending elements.

Call :meth:`peek` on the result to get the value that will be returned
by :func:`next`. This won't advance the iterator:

    >>> p = peekable(['a', 'b'])
    >>> p.peek()
    'a'
    >>> next(p)
    'a'

Pass :meth:`peek` a default value to return that instead of raising
``StopIteration`` when the iterator is exhausted.

    >>> p = peekable([])
    >>> p.peek('hi')
    'hi'

peekables also offer a :meth:`prepend` method, which "inserts" items
at the head of the iterable:

    >>> p = peekable([1, 2, 3])
    >>> p.prepend(10, 11, 12)
    >>> next(p)
    10
    >>> p.peek()
    11
    >>> list(p)
    [11, 12, 1, 2, 3]

peekables can be indexed. Index 0 is the item that will be returned by
:func:`next`, index 1 is the item after that, and so on:
The values up to the given index will be cached.

    >>> p = peekable(['a', 'b', 'c', 'd'])
    >>> p[0]
    'a'
    >>> p[1]
    'b'
    >>> next(p)
    'a'

Negative indexes are supported, but be aware that they will cache the
remaining items in the source iterator, which may require significant
storage.

To check whether a peekable is exhausted, check its truth value:

    >>> p = peekable(['a', 'b'])
    >>> if p:  # peekable has items
    ...     list(p)
    ['a', 'b']
    >>> if not p:  # peekable is exhausted
    ...     list(p)
    []

Constructor & Destructor Documentation

◆ __init__()

def __init__ (   self,
  iterable 
)

Member Function Documentation

◆ __bool__()

def __bool__ (   self)

◆ __getitem__()

def __getitem__ (   self,
  index 
)

◆ __iter__()

def __iter__ (   self)

◆ __next__()

def __next__ (   self)

◆ peek()

def peek (   self,
  default = _marker 
)
Return the item that will be next returned from ``next()``.

Return ``default`` if there are no items left. If ``default`` is not
provided, raise ``StopIteration``.

◆ prepend()

def prepend (   self,
items 
)
Stack up items to be the next ones returned from ``next()`` or
``self.peek()``. The items will be returned in
first in, first out order::

    >>> p = peekable([1, 2, 3])
    >>> p.prepend(10, 11, 12)
    >>> next(p)
    10
    >>> list(p)
    [11, 12, 1, 2, 3]

It is possible, by prepending items, to "resurrect" a peekable that
previously raised ``StopIteration``.

    >>> p = peekable([])
    >>> next(p)
    Traceback (most recent call last):
      ...
    StopIteration
    >>> p.prepend(1)
    >>> next(p)
    1
    >>> next(p)
    Traceback (most recent call last):
      ...
    StopIteration

The documentation for this class was generated from the following file: