rdkit.DataStructs.LazySignature

Package rdkit :: Package DataStructs :: Module LazySignature |
[hide private]
[frames] | no frames]

# Source Code for Module rdkit.DataStructs.LazySignature

     1  # $Id$
     2  #
     3  #  Copyright (C) 2005 Rational Discovery LLC
     4  #   All Rights Reserved
     5  #
     6
     7
     8 -class LazySig:
     9
    10 -  def __init__(self, computeFunc, sigSize):
    11      """
    12      computeFunc should take a single argument, the integer bit id
    13      to compute
    14
    15      """
    16      if sigSize <= 0:
    17        raise ValueError('zero size')
    18      self.computeFunc = computeFunc
    19      self.size = sigSize
    20      self._cache = {}
    21
    22 -  def __len__(self):
    23      """
    24
    25       >>> obj = LazySig(lambda x:1,10)
    26       >>> len(obj)
    27       10
    28
    29      """
    30      return self.size
    31
    32 -  def __getitem__(self, which):
    33      """
    34
    35       >>> obj = LazySig(lambda x:x,10)
    36       >>> obj[1]
    37       1
    38       >>> obj[-1]
    39       9
    40       >>> try:
    41       ...   obj[10]
    42       ... except IndexError:
    43       ...   1
    44       ... else:
    45       ...   0
    46       1
    47       >>> try:
    48       ...   obj[-10]
    49       ... except IndexError:
    50       ...   1
    51       ... else:
    52       ...   0
    53       1
    54
    55      """
    56      if which < 0:
    57        # handle negative indices
    58        which = self.size + which
    59
    60      if which <= 0 or which >= self.size:
    61        raise IndexError('bad index')
    62
    63      if which in self._cache:
    64        v = self._cache[which]
    65      else:
    66        v = self.computeFunc(which)
    67        self._cache[which] = v
    68      return v
    69
    70
    71  # ------------------------------------
    72  #
    73  #  doctest boilerplate
    74  #
    75 -def _runDoctests(verbose=None):  # pragma: nocover
    76    import sys
    77    import doctest
    78    failed, _ = doctest.testmod(optionflags=doctest.ELLIPSIS, verbose=verbose)
    79    sys.exit(failed)
    80
    81
    82  if __name__ == '__main__':  # pragma: nocover
    83    _runDoctests()
    84