1 class AdaptationError(TypeError):
3 class LiskovViolation(AdaptationError):
6 _adapter_factory_registry = {}
8 def registerAdapterFactory(objtype, protocol, factory):
9 _adapter_factory_registry[objtype, protocol] = factory
11 def unregisterAdapterFactory(objtype, protocol):
12 del _adapter_factory_registry[objtype, protocol]
14 def _adapt_by_registry(obj, protocol, alternate):
15 factory = _adapter_factory_registry.get((type(obj), protocol))
19 adapter = factory(obj, protocol, alternate)
20 if adapter is AdaptationError:
21 raise AdaptationError,obj
26 def adapt(obj, protocol, alternate=AdaptationError):
30 # (a) first check to see if object has the exact protocol
35 # (b) next check if t.__conform__ exists & likes protocol
36 conform = getattr(t, '__conform__', None)
37 if conform is not None:
38 result = conform(obj, protocol)
39 if result is not None:
42 # (c) then check if protocol.__adapt__ exists & likes obj
43 adapt = getattr(type(protocol), '__adapt__', None)
45 result = adapt(protocol, obj)
46 if result is not None:
48 except LiskovViolation:
51 # (d) check if object is instance of protocol
53 if isinstance(obj, protocol):
58 # (e) last chance: try the registry
59 return _adapt_by_registry(obj, protocol, alternate)