-def create_handle(connection, type, *args):
- handle = _HANDLE_TYPE_MAPPING[type](connection, *args)
- connection._handles[handle.get_type(), handle.get_id()] = handle
- return handle
+def create_handle_factory():
+
+ cache = weakref.WeakValueDictionary()
+
+ def _create_handle(connection, type, *args):
+ Handle = _HANDLE_TYPE_MAPPING[type]
+ key = Handle, connection.username, args
+ try:
+ handle = cache[key]
+ isNewHandle = False
+ except KeyError:
+ # The misnamed get_handle_id requests a new handle id
+ handle = Handle(connection, connection.get_handle_id(), *args)
+ cache[key] = handle
+ isNewHandle = True
+ connection._handles[handle.get_type(), handle.get_id()] = handle
+ if isNewHandle:
+ handleStatus = "Is New!" if isNewHandle else "From Cache"
+ _moduleLogger.debug("Created Handle: %r (%s)" % (handle, handleStatus))
+ return handle
+
+ return _create_handle
+
+
+create_handle = create_handle_factory()