render_object_constructor

render_object_constructor#

treescope.repr_lib.render_object_constructor(object_type: type[Any], attributes: Mapping[str, Any], path: str | None, subtree_renderer: renderers.TreescopeSubtreeRenderer, roundtrippable: bool = False, color: str | None = None) rendering_parts.Rendering[source]#

Renders an object in “constructor format”, similar to a dataclass.

This produces a rendering like Foo(bar=1, baz=2), where Foo identifies the type of the object, and bar and baz are the names of the attributes of the object. It is a requirement that these are the actual attributes of the object, which can be accessed via obj.bar or similar; otherwise, the path renderings will break.

This can be used from within a __treescope_repr__ implementation via

def __treescope_repr__(self, path, subtree_renderer):
  return repr_lib.render_object_constructor(
      object_type=type(self),
      attributes=<dict of attributes here>,
      path=path,
      subtree_renderer=subtree_renderer,
  )
Parameters:
  • object_type – The type of the object.

  • attributes – The attributes of the object, which will be rendered as keyword arguments to the constructor.

  • path – The path to the object. When render_object_constructor is called from __treescope_repr__, this should come from the path argument to __treescope_repr__.

  • subtree_renderer – The renderer to use to render subtrees. When render_object_constructor is called from __treescope_repr__, this should come from the subtree_renderer argument to __treescope_repr__.

  • roundtrippable – Whether evaluating the rendering as Python code will produce an object that is equal to the original object. This implies that the keyword arguments are actually the keyword arguments to the constructor, and not some other attributes of the object.

  • color – The background color to use for the object rendering. If None, does not use a background color. A utility for assigning a random color based on a string key is given in treescope.formatting_util.

Returns:

A rendering of the object, suitable for returning from __treescope_repr__.