I am implementing a simple 'named tuple' type mechanism, which has read-only attributes instead of read/write.
def ReadOnlyNamedTuple( *fields ):
class Base( object ):
_fields = fields[:]
def __init__( self, *values ):
assert len(values) == len(Base._fields), "Incorrect number of arguments, expected %d" % len(Base._fields)
self._field_values = dict( zip( Base._fields, values ) )
def __getitem__( self, i ):
return self._field_values[ Base._fields[i] ]
def __len__(self):
return len( self._field_values )
# attach the fields to the class with properties:
for attr in fields :
fn = lambda s : s._field_values[attr]
fn = property( fn )
setattr( Base, attr, fn )
return Base
When I execute this, the last "getter" lambda function seems to be attached to all properties.
>>>
>>> C = ReadOnlyNamedTuple( 'a','b','c' )
>>> c = C( 1, 2, 3 )
>>> c[0]
1
>>> c[1]
2
>>> c[2]
3
>>> c.a
3
>>> c.b
3
>>> c.c
3
>>> c._field_values
{'a': 1, 'c': 3, 'b': 2}
Seems silly, but I can't figure out why the properties are not being attached correctly. Suggestions?