comm.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. """Base class for a Comm"""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. import uuid
  5. from typing import Optional
  6. from warnings import warn
  7. import comm.base_comm
  8. import traitlets.config
  9. from traitlets import Bool, Bytes, Instance, Unicode, default
  10. from ipykernel.jsonutil import json_clean
  11. from ipykernel.kernelbase import Kernel
  12. # this is the class that will be created if we do comm.create_comm
  13. class BaseComm(comm.base_comm.BaseComm): # type:ignore[misc]
  14. """The base class for comms."""
  15. kernel: Optional["Kernel"] = None
  16. def publish_msg(self, msg_type, data=None, metadata=None, buffers=None, **keys):
  17. """Helper for sending a comm message on IOPub"""
  18. if not Kernel.initialized():
  19. return
  20. data = {} if data is None else data
  21. metadata = {} if metadata is None else metadata
  22. content = json_clean(dict(data=data, comm_id=self.comm_id, **keys))
  23. if self.kernel is None:
  24. self.kernel = Kernel.instance()
  25. assert self.kernel.session is not None
  26. self.kernel.session.send(
  27. self.kernel.iopub_socket,
  28. msg_type,
  29. content,
  30. metadata=json_clean(metadata),
  31. parent=self.kernel.get_parent(),
  32. ident=self.topic,
  33. buffers=buffers,
  34. )
  35. # but for backwards compatibility, we need to inherit from LoggingConfigurable
  36. class Comm(BaseComm, traitlets.config.LoggingConfigurable):
  37. """Class for communicating between a Frontend and a Kernel"""
  38. kernel = Instance("ipykernel.kernelbase.Kernel", allow_none=True)
  39. comm_id = Unicode()
  40. primary = Bool(True, help="Am I the primary or secondary Comm?")
  41. target_name = Unicode("comm")
  42. target_module = Unicode(
  43. None,
  44. allow_none=True,
  45. help="""requirejs module from
  46. which to load comm target.""",
  47. )
  48. topic = Bytes()
  49. @default("kernel")
  50. def _default_kernel(self):
  51. if Kernel.initialized():
  52. return Kernel.instance()
  53. return None
  54. @default("comm_id")
  55. def _default_comm_id(self):
  56. return uuid.uuid4().hex
  57. def __init__(
  58. self, target_name="", data=None, metadata=None, buffers=None, show_warning=True, **kwargs
  59. ):
  60. """Initialize a comm."""
  61. if show_warning:
  62. warn(
  63. "The `ipykernel.comm.Comm` class has been deprecated. Please use the `comm` module instead."
  64. "For creating comms, use the function `from comm import create_comm`.",
  65. DeprecationWarning,
  66. stacklevel=2,
  67. )
  68. # Handle differing arguments between base classes.
  69. had_kernel = "kernel" in kwargs
  70. kernel = kwargs.pop("kernel", None)
  71. if target_name:
  72. kwargs["target_name"] = target_name
  73. BaseComm.__init__(self, data=data, metadata=metadata, buffers=buffers, **kwargs) # type:ignore[call-arg]
  74. # only re-add kernel if explicitly provided
  75. if had_kernel:
  76. kwargs["kernel"] = kernel
  77. traitlets.config.LoggingConfigurable.__init__(self, **kwargs)
  78. __all__ = ["Comm"]