1"""
2A number of Cocoa API's have a 'context' argument that is a plain 'void*'
3in ObjC, and an Integer value in Python.  The 'context' object defined here
4allows you to get a unique integer number that can be used as the context
5argument for any Python object, and retrieve that object later on using the
6context number.
7
8Usage::
9
10    ...
11    ctx = objc.context.register(myContext)
12    someObject.observeValueForKeyPath_ofObject_change_context_(
13        kp, obj, {}, ctx)
14    ...
15
16and in the callback::
17
18    def observeValueForKeyPath_ofObject_change_context_(self,
19        kp, obj, change, ctx):
20
21        myContext = objc.context.get(ctx)
22        ...
23
24Use ``objc.context.unregister`` to remove the registration of ``myObject``
25when you're done. The argument to unregister is the same object as was
26passed in during registration.
27"""
28
29__all__ = ('context',)
30
31class ContextRegistry (object):
32    def __init__(self):
33        self._registry = {}
34
35    def register(self, object):
36        uniq = id(object)
37        self._registry[uniq] = object
38        return uniq
39
40    def unregister(self, object):
41        try:
42            del self._registry[id(object)]
43        except KeyError:
44            pass
45
46    def get(self, uniq):
47        return self._registry[uniq]
48
49context = ContextRegistry()
50