+class StringMapping(collections.MutableMapping):
+ def __init__(self, instance, prop):
+ self.stringclass = prop.stringclass
+ self.instance = instance
+ self.strings = getattr(instance, prop.stringclass._attrname)
+ self.colname = prop.colname
+
+ def __len__(self):
+ return len(self.strings)
+
+ def __iter__(self):
+ return iter(self.strings)
+
+ def __contains__(self, lang):
+ return lang in self.strings
+
+ def __getitem__(self, lang):
+ return getattr(self.strings[lang], self.colname)
+
+ def __setitem__(self, lang, value):
+ try:
+ # Modifying an existing row
+ row = self.strings[lang]
+ except KeyError:
+ # We need do add a whole row for the language
+ row = self.stringclass()
+ row.object_id = self.instance.id
+ session = object_session(self.instance)
+ if isinstance(lang, basestring):
+ lang = session.query(Language).filter_by(
+ identifier=lang).one()
+ row.language = lang
+ self.strings[lang] = row
+ session.add(row)
+ return setattr(row, self.colname, value)
+
+ def __delitem__(self, lang):
+ raise NotImplementedError('Cannot delete a single string. '
+ 'Perhaps you wan to delete all of %s.%s?' %
+ (self.instance, self.stringclass._attrname)
+ )
+