1
##############################################################################
3
# Copyright (c) 2006-2007 Zope Corporation and Contributors.
6
# This software is subject to the provisions of the Zope Public License,
7
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
8
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
9
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
10
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
11
# FOR A PARTICULAR PURPOSE.
13
##############################################################################
14
"""A source proxy providing a mapping between values
17
__docformat__ = "reStructuredText"
20
import zope.schema.interfaces
23
class ValueMappingSourceContextBinder(object):
25
zope.interface.implements(zope.schema.interfaces.IContextSourceBinder)
27
def __init__(self, base, map):
31
def __call__(self, context):
32
source = self.base(context)
33
return ValueMappingSource(source, self.map)
36
class ValueMappingSource(object):
38
zope.interface.implements(zope.schema.interfaces.IIterableSource)
40
def __init__(self, base, map):
42
self._mapping_cache = {}
45
def mapReverse(self, mapped_value):
46
if mapped_value in self._mapping_cache:
47
return self._mapping_cache[mapped_value]
49
# Not found in cache, continue to look for the mapped value in
50
# the rest of the iterator
51
if not hasattr(self, '_cache_iterator'):
52
self._cache_iterator = iter(self.base)
53
for original_value in self._cache_iterator:
54
original_mapped_value = self.map(original_value)
55
self._mapping_cache[original_mapped_value] = original_value
56
if mapped_value == original_mapped_value:
58
raise KeyError(mapped_value)
60
def __contains__(self, value):
62
self.mapReverse(value)
69
for item in self.base:
75
def __nonzero__(self):
76
for dummy in self.base: