MCPcopy Index your code
hub / github.com/pyscript/pyscript / _get_content_and_mime

Function _get_content_and_mime

core/src/stdlib/pyscript/display.py:130–181  ·  view source on GitHub ↗

Returns the formatted raw content to be inserted into the DOM representing the given object, along with the object's detected MIME type. Returns a tuple of (html_string, mime_type). Prefers _repr_mimebundle_ if available, otherwise tries individual representation methods, fall

(obj)

Source from the content-addressed store, hash-verified

128
129
130def _get_content_and_mime(obj):
131 """
132 Returns the formatted raw content to be inserted into the DOM representing
133 the given object, along with the object's detected MIME type.
134
135 Returns a tuple of (html_string, mime_type).
136
137 Prefers _repr_mimebundle_ if available, otherwise tries individual
138 representation methods, falling back to __repr__ (with a warning in
139 the console).
140
141 Implements a subset of IPython's rich display system (mimebundle support,
142 etc...).
143 """
144 if isinstance(obj, str):
145 return html.escape(obj), "text/plain"
146 # Prefer an object's mimebundle.
147 mimebundle = _get_representation(obj, "_repr_mimebundle_")
148 if mimebundle:
149 if isinstance(mimebundle, tuple):
150 # Grab global metadata.
151 format_dict, global_meta = mimebundle
152 else:
153 format_dict, global_meta = mimebundle, {}
154 # Try to render using mimebundle formats.
155 for mime_type, output in format_dict.items():
156 if mime_type in _MIME_TO_RENDERERS:
157 meta = global_meta.get(mime_type, {})
158 # If output is a tuple, merge format-specific metadata.
159 if isinstance(output, tuple):
160 output, format_meta = output
161 meta.update(format_meta)
162 return _MIME_TO_RENDERERS[mime_type](output, meta), mime_type
163 # No mimebundle or no available renderers therein, so try individual
164 # methods.
165 for method, mime_type in _METHOD_TO_MIME.items():
166 if mime_type not in _MIME_TO_RENDERERS:
167 continue
168 output = _get_representation(obj, method)
169 if output is None:
170 continue
171 meta = {}
172 if isinstance(output, tuple):
173 output, meta = output
174 return _MIME_TO_RENDERERS[mime_type](output, meta), mime_type
175 # Ultimate fallback to repr with warning.
176 window.console.warn(
177 f"Object {type(obj).__name__} has no supported representation method. "
178 "Using __repr__ as fallback."
179 )
180 output = repr(obj)
181 return html.escape(output), "text/plain"
182
183
184def _write_to_dom(element, value, append):

Callers 1

_write_to_domFunction · 0.85

Calls 4

_get_representationFunction · 0.85
warnMethod · 0.80
getMethod · 0.45
updateMethod · 0.45

Tested by

no test coverage detected