Package pyplusplus :: Package code_repository :: Module named_tuple |

# Source Code for Module pyplusplus.code_repository.named_tuple

     1  # Copyright 2004-2008 Roman Yakovenko.
     2  # Distributed under the Boost Software License, Version 1.0. (See
     3  # accompanying file LICENSE_1_0.txt or copy at
     4  # http://www.boost.org/LICENSE_1_0.txt)
     5
     6  file_name = "named_tuple.py"
     7
     8  code = \
     9  """# Copyright 2004-2008 Roman Yakovenko.
    10  # Distributed under the Boost Software License, Version 1.0. (See
    11  # accompanying file LICENSE_1_0.txt or copy at
    12  # http://www.boost.org/LICENSE_1_0.txt)
    13
    14  class named_tuple(tuple):
    15      \"\"\"Creates tuple, which allows access to stored values by name and\\or by index.
    16
    17      Construction example: named_tuple( ('a',0), ('b',1) )
    18          'a' and 'b' are names, while 0 and 1 are values
    19      \"\"\"
    20
    21      def __new__(cls, *args):
    22          return tuple.__new__( cls, [ val for name, val in args] )
    23
    24      def __init__(self, *args):
    25          tuple.__init__( self )
    26          self.__dict__[ '__name2value' ] = dict( args )
    27
    28      def __getattr__(self, name):
    29          try:
    30              return self.__dict__['__name2value'][ name ]
    31          except KeyError:
    32              raise AttributeError( "named_tuple has no attribute '%s'" % name )
    33
    34      def __setattr__(self, name, value):
    35          raise AttributeError( "named_tuple has no attribute '%s'" % name )
    36
    37      def __getitem__( self, key ):
    38          #TODO: it could be nice to support slicing. So the __getitem__ in case of
    39          #slicing will return new named_tuple.
    40          if isinstance( key, basestring ):
    41              return self.__dict__['__name2value'][ key ]
    42          else:
    43              return super( named_tuple, self ).__getitem__( key )
    44
    45  if __name__ == '__main__':
    46      nt = named_tuple( ('a',0), ('b',1) )
    47      assert nt.a == 0 and nt.b == 1
    48      a,b = nt
    49      assert a == 0 and b == 1
    50      assert nt[ "a" ] == 0 and nt[ "b" ] == 1
    51
    52  """
    53