google / langfun

OO for LLMs
Apache License 2.0
100 stars 17 forks source link

Add `lf.repr_utils` for helping handle shared content in `_repr_html_`. #231

Closed copybara-service[bot] closed 1 month ago

copybara-service[bot] commented 1 month ago

Add lf.repr_utils for helping handle shared content in _repr_html_.

Multiple objects rendered in the same HTML might share styles and scripts. By adding lf.repr_utils, users could deal with shared content when implementing _repr_html_. For example:

class Foo(pg.Object):
  def _repr_html_(self) -> str:
    s = io.StringIO()
    lf.repr_utils.write_maybe_shared(s, '<style>..</style>')
    lf.repr_utils.write_maybe_shared(s, '<script>..</script>')
    return s.getvalue()

with lf.repr_utils.share_parts():
  # The <style> and <script> section will be written only once.
  console.display(Foo())
  console.display(Foo())