I have a bunch of dictionaries, which I would like to annotate with type information, to be able to later get adapters for them. In the following example, the failing case is what I would like to do and the other case shows a working version. Is it somehow possible to get the first version working without introducing the extra object? The code which creates the dicts would not be easy to change, so I'm looking for the most simple and non intrusive way to add some type infos.
from zope.interface import Interface, implements, directlyProvides
from zope.interface.registry import Components
registry = Components()
class IA(Interface):
pass
# this one fails
data = {}
directlyProvides(data, IA)
# this way it works
class X(dict):
pass
data = X()
directlyProvides(data, IA)
You cannot annotate Python built-in types with interface information; you simply cannot add the required attributes.
You can register adapters for the type (so no interfaces implemented):
You cannot do this for instances, unfortunately:
This means that if you really must adapt specific dictionaries, then your options are limited. Using a subclass of
dictis one work-around.However, you must really ask if adapting dictionaries is the best approach for your problem here.