Repository navigation
Expand file tree
/
Copy pathaddin_values.py
More file actions
585 lines (481 loc) · 24.1 KB
/
Copy pathaddin_values.py
File metadata and controls
585 lines (481 loc) · 24.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# WriterAgent - AI Writing Assistant for LibreOffice
# Copyright (c) 2024 John Balis
# Copyright (c) 2026 KeithCu (modifications and relicensing)
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Calc add-in value conversion, error mapping, and result coercion helpers.
Cell outcomes for ``=PY()`` fall into four kinds:
- **Payload NaN** (quiet NaN carrying a Calc ``FormulaError`` in its low 32 bits):
``py_addin_cell_value`` (error tokens and helper error dicts),
``addin_result_for_worker_status`` (failed worker runs other than setup/stop codes),
and the worker's ``NA_NAN``, ``NESTED_ARRAY_NAN``, and ``DIV0_NAN`` (``calc_functions_util.py``).
LibreOffice's ``GetDoubleErrorValue`` (``include/formula/errorcodes.hxx``) reads
``nan_parts.fraction_lo`` and ``ScInterpreter::PushDouble``
(``sc/source/core/tool/interpr4.cxx``) turns it into a Calc error so ``ISERROR`` is true.
- **Spill neighbour error or void**: ``coerce_spill_value`` returns a ``SpillValue``
with ``kind == "err"`` for error tokens and non-finite values, and ``spill.perform_deferred_spill``
writes ``setDataArray`` of ``None`` (UNO void,
which ``lcl_PutDataArray`` in ``sc/source/ui/unoobj/cellsuno.cxx`` turns into
``FormulaError::NotAvailable`` / ``#N/A``) or ``=#ERRn!`` formulas.
- **``"#SPILL!"`` text**: ``spill.prepare_auto_spill``, returned by
``function.finalize_python_return`` (``ISERROR`` is false).
- **``"Error: …"`` text**: setup and stop worker codes in
``addin_result_for_worker_status``, host exceptions in
``format_addin_error_for_display``, size errors in ``function.py``,
and missing-caller in ``addin_impl.py``. Write tools recognise this kind
with ``is_failed_run_text``.
Worker failure codes in ``addin_result_for_worker_status`` map as follows:
- ``VENV_NOT_FOUND`` → venv guidance text (``Settings → Python``).
- ``VENV_TIMEOUT``, ``EXECUTION_TIMEOUT`` → timeout guidance text (``Settings → Python``).
- ``USER_STOPPED`` → ``"Error:"`` plus the message via ``_error_cell_text``.
- Any other code (including a missing code) → payload NaN selected by
``worker_exception_error_code``.
``LO_ERROR_TOKENS`` in ``plugin/scripting/venv/coerce.py`` mirrors
``_CALC_ERROR_TOKEN_CODES``; ``tests/calc/python/test_addin_values.py`` pins that both
agree. ``calc_error_code_for_token`` maps those tokens plus published ``Err:<n>``
codes (case-insensitive).
"""
from __future__ import annotations
from dataclasses import dataclass
import datetime
import functools
import logging
import math
import re
import struct
from typing import Any, TypeGuard, cast
from com.sun.star.uno import RuntimeException
from plugin.calc.datetime_wire import (
datetime_serial,
duration_serial_from_iso,
match_iso_duration,
match_iso_temporal,
time_day_fraction,
)
from plugin.framework.errors import format_error_message
from plugin.framework.i18n import _
from plugin.framework.uno_context import uno_any
log = logging.getLogger(__name__)
_CALC_ERROR_TOKEN_CODES: dict[str, int] = {
"#VALUE!": 519,
"#NUM!": 503,
"#DIV/0!": 532,
"#N/A": 0x7FFF,
"#N/A N/A": 0x7FFF,
"#REF!": 524,
"#NAME?": 525,
"#NULL!": 521,
}
# Same spelling as coerce._ERR_NUMBER_RE in the worker.
_ERR_NUMBER_RE = re.compile(r"Err:([0-9]{3})", re.IGNORECASE)
# isPublishedFormulaError (include/formula/errorcodes.hxx). =#ERRn! with any other number is #NAME?,
# and a payload NaN with 537 (RetryCircular) starts Calc's recursion handling.
_PUBLISHED_ERROR_CODES = frozenset({*range(501, 505), *range(507, 526), *range(530, 534), *range(538, 541)})
_ERR_VALUE = _CALC_ERROR_TOKEN_CODES["#VALUE!"]
_ERR_NUM = _CALC_ERROR_TOKEN_CODES["#NUM!"]
ERR_NA = _CALC_ERROR_TOKEN_CODES["#N/A"]
_WORKER_EXC_CODES: dict[str, int] = {
"ZeroDivisionError": _CALC_ERROR_TOKEN_CODES["#DIV/0!"],
"OverflowError": _CALC_ERROR_TOKEN_CODES["#NUM!"],
"FloatingPointError": _CALC_ERROR_TOKEN_CODES["#NUM!"],
"NameError": _CALC_ERROR_TOKEN_CODES["#NAME?"],
"UnboundLocalError": _CALC_ERROR_TOKEN_CODES["#NAME?"],
}
_DUE_TO_EXC_RE = re.compile(r" due to: ([A-Za-z_][A-Za-z0-9_]*): ")
# Worker result codes whose run never reached a verdict on the user's code.
# These and VENV_NOT_FOUND / USER_STOPPED stay text (table in the module
# docstring); every other code is a payload NaN so ISERROR sees it.
_TIMEOUT_CODES: frozenset[str] = frozenset({"VENV_TIMEOUT", "EXECUTION_TIMEOUT"})
def calc_formula_error_double(code: int) -> float:
"""Return a quiet-NaN double carrying a LibreOffice FormulaError code in its low bits.
In LibreOffice Calc (interpr4.cxx TreatDoubleError and formula/errorcodes.hxx
GetDoubleErrorValue), ScInterpreter::PushDouble checks for non-finite doubles.
If the double is a quiet NaN, GetDoubleErrorValue inspects the low 32 bits
(fraction_lo). If fraction_lo matches a valid FormulaError code, PushError is called
with that code instead of storing a standard float. A plain NaN (fraction_lo == 0)
evaluates to FormulaError::IllegalFPOperation (#NUM!) only; encoding the integer error
code into fraction_lo allows returning #VALUE!, #DIV/0!, #REF!, #NAME?, #NULL!, etc.
"""
bits = 0x7FF8000000000000 | (code & 0xFFFF)
return struct.unpack("d", struct.pack("Q", bits))[0]
def nonfinite_error_code(val: float) -> int:
"""FormulaError code LibreOffice reads from a NaN or infinity (GetDoubleErrorValue, include/formula/errorcodes.hxx).
A code ``=#ERRn!`` cannot express becomes 503 (#NUM!), because Calc compiles an unpublished number to #NAME?.
``low == 0`` and infinities still give 503; high bits still give 519.
"""
low = struct.unpack("Q", struct.pack("d", val))[0] & 0xFFFFFFFF
if low & 0xFFFF0000:
return _ERR_VALUE
return low if low == ERR_NA or low in _PUBLISHED_ERROR_CODES else _ERR_NUM
def published_err_code(text: str) -> int | None:
"""FormulaError integer when *text* is a published ``Err:<n>`` token (case-insensitive), else None."""
match = _ERR_NUMBER_RE.fullmatch(text.strip())
if match is None:
return None
code = int(match.group(1))
return code if code in _PUBLISHED_ERROR_CODES else None
def calc_error_code_for_token(text: str) -> int | None:
code = published_err_code(text)
if code is not None:
return code
return _CALC_ERROR_TOKEN_CODES.get(text.strip())
def worker_exception_error_code(message: str) -> int:
matches = _DUE_TO_EXC_RE.findall(message)
if matches:
return _WORKER_EXC_CODES.get(matches[-1], _ERR_VALUE)
return _ERR_VALUE
_HELPER_ERROR_DICT_KEYS = frozenset({"status", "code", "message", "helper", "details"})
def is_helper_error_dict(val: Any) -> TypeGuard[dict[str, Any]]:
"""True only for the dict ``error_result`` builds (``plugin/scripting/venv/results.py``).
status, code, and message are always set. helper and details are set only
when those arguments are truthy. Success payloads and other error dicts
carry more keys. Do not import the venv module for this check.
"""
if not isinstance(val, dict):
return False
if not set(val).issubset(_HELPER_ERROR_DICT_KEYS):
return False
if "code" not in val or "message" not in val:
return False
if val.get("status") != "error":
return False
code = val.get("code")
message = val.get("message")
if not isinstance(code, str) or not code.strip():
return False
if not isinstance(message, str):
return False
if "helper" in val:
helper = val["helper"]
if not isinstance(helper, str) or not helper.strip():
return False
if "details" in val and not isinstance(val["details"], dict):
return False
return True
def _calc_code_for_helper_error(code: str) -> int:
"""FormulaError integer for a helper error code.
Tokens and published ``Err:<n>`` strings use ``calc_error_code_for_token``.
Exception names use ``_WORKER_EXC_CODES`` (the ``worker_exception_error_code`` table).
Anything else is #VALUE! (519). The helper message is not scanned.
"""
token_code = calc_error_code_for_token(code)
if token_code is not None:
return token_code
return _WORKER_EXC_CODES.get(code.strip(), _ERR_VALUE)
def helper_error_log_message(err: dict[str, Any]) -> str:
code = str(err["code"]).strip()
message = str(err["message"])
helper = err.get("helper")
if isinstance(helper, str) and helper.strip():
return f"{helper.strip()}: {code}: {message}"
return f"{code}: {message}"
def _map_addin_error_tokens(val: Any) -> Any:
if isinstance(val, str):
code = calc_error_code_for_token(val)
if code is not None:
return calc_formula_error_double(code)
return val
if isinstance(val, tuple):
return tuple(_map_addin_error_tokens(elem) for elem in val)
return val
def py_addin_cell_value(val: Any) -> float | str | tuple[Any, ...]:
"""Return the LibreOffice Calc add-in cell value for a Python result.
This maps formula error tokens (e.g. #VALUE!, #DIV/0!) into quiet-NaN doubles
carrying Calc FormulaError codes. A helper error dict is mapped the same way.
to_calc_compatible itself remains a type coercion so quant/tabular egress
keeps dicts and token strings as text.
"""
if is_helper_error_dict(val):
# Helper error dicts must become calc_formula_error_double, not cell text, so ISERROR sees a real formula error.
log.error("=PY() worker failure: %s", helper_error_log_message(val))
return calc_formula_error_double(_calc_code_for_helper_error(val["code"]))
return cast("float | str | tuple[Any, ...]", _map_addin_error_tokens(to_calc_compatible(val)))
def _matrix_cell_value(cell: Any) -> float | str:
val = py_addin_cell_value(cell)
if isinstance(val, (float, str)):
return val
# Nested sequences have no cell representation in Calc matrices; surface #VALUE! instead of a blank.
return calc_formula_error_double(_ERR_VALUE)
@functools.cache
def accepts_returned_any(ctx: Any) -> bool:
"""Whether this PyUNO lets a Python UNO method return ``uno.Any``; *ctx* is any PyUNO proxy.
LibreOffice 26.8 does (commits 1e2e9a20a419 and 507b6c2b907c). Before that,
``Adapter::invoke`` (``pyuno/source/module/pyuno_adapter.cxx``) throws and Calc shows
``#VALUE!``. 507b6c2b907c removed the same rejection from method arguments, so an
accepted ``uno.Any`` argument means an accepted return value. This asks PyUNO rather
than the version number because Collabora Office 26.04 has the change too.
"""
try:
ctx.getValueByName(uno_any("string", ""))
except RuntimeException:
return False
return True
def matrix_result(ctx: Any, result: list[Any] | tuple[Any, ...]) -> Any:
"""Wrap a list or 2D grid for Calc's add-in bridge.
Calc evaluates ``{=PY()}`` once per array block (``ScInterpreter::ScExternal``,
``sc/source/core/tool/interpr4.cxx``). A bare Python tuple of tuples reaches Calc
as ``[]any`` and fails with ``#VALUE!``, so the grid is wrapped in a typed
``uno.Any``. PyUNO accepts that as a return value from LibreOffice 26.8
(``accepts_returned_any``); before that, the top-left value is returned (``""``
for an empty first row), and Calc repeats it over an array block.
A 1x1 grid returns a scalar so Calc interns text, and an all-text grid uses
``[][]string`` so ``ScUnoAddInCall::SetResult`` (``sc/source/core/tool/addincol.cxx``)
interns via ``mrDoc.GetSharedStringPool().intern``. Mixed grids use ``[][]any``;
note that ``ScSequenceToMatrix::CreateMixedMatrix`` (``sc/source/core/tool/rangeseq.cxx``)
stores ``svl::SharedString(aUStr)`` with null ``mpDataIgnoreCase``, so Calc
string equality (``=``, ``COUNTIF``) on text cells in a mixed block fails and
two different texts can compare equal.
"""
grid = result_as_spill_grid(result)
if not grid or not any(grid):
return ""
rows = tuple(tuple(_matrix_cell_value(cell) for cell in row) for row in grid)
corner = rows[0][0] if rows[0] else ""
if (len(rows) == 1 and len(rows[0]) == 1) or not accepts_returned_any(ctx):
return corner
all_str = all(isinstance(cell, str) for row in rows for cell in row)
uno_type = "[][]string" if all_str else "[][]any"
log.debug("PYTHON matrix_result: type=%s rows=%d", uno_type, len(rows))
return uno_any(uno_type, rows)
def _venv_not_found_text() -> str:
return _("Error: Python venv not found. Open Settings → Python, set the venv path, then Test.")
def _timed_out_text() -> str:
return _("Error: Python timed out. Open Settings → Python to raise the timeout, or Test the venv.")
def _main_thread_timeout_template() -> str:
return _("Error: Main-thread execution timed out ({0})")
def _error_text_template() -> str:
return _("Error: {0}")
def is_failed_run_text(text: str) -> bool:
"""True when *text* is the "Error: …" cell text of a failed =PY run (module docstring).
User code that returns such text itself is indistinguishable and counts too.
"""
prefixes = (
"Error:",
_venv_not_found_text(),
_timed_out_text(),
_error_text_template().partition("{0}")[0].strip(),
_main_thread_timeout_template().partition("{0}")[0].strip(),
)
# An empty prefix would match everything.
return text.startswith(tuple(p for p in prefixes if p))
def addin_result_for_worker_status(res: dict[str, Any]) -> float | str:
"""Return add-in cell result for non-ok worker status (payload NaN error or text message).
Setup and stop codes stay text so the user sees actionable guidance; every other
failure returns a quiet-NaN with FormulaError payload so ISERROR behaves correctly.
"""
code = res.get("code")
message = str(res.get("message") or res.get("error") or "")
if code == "VENV_NOT_FOUND":
return _venv_not_found_text()
if code in _TIMEOUT_CODES:
return _timed_out_text()
if code == "USER_STOPPED":
return _error_cell_text(message)
log.error("=PY() worker failure: %s", message)
return calc_formula_error_double(worker_exception_error_code(message))
def _naive_datetime(dt: datetime.datetime) -> datetime.datetime:
return dt.replace(tzinfo=None)
def _calc_iso_datetime(dt: datetime.datetime) -> str:
"""Naive ISO-8601. Calc does not parse offset-bearing stamps as dates."""
return _naive_datetime(dt).isoformat()
def to_stdlib_temporal(val: Any) -> Any:
"""Pandas / numpy temporal values as stdlib datetime, date, time, timedelta, None (missing)
or text (units finer than a microsecond); anything else is returned unchanged.
The formula cell shows temporals as ISO text because the add-in bridge returns one
scalar and a bare serial would display as a number; spill neighbours get day serials
plus a number format because they are ordinary cells.
"""
# pd.NaT subclasses datetime but isoformat() raises; check before isinstance(..., datetime).
if type(val).__name__ in ("NaTType", "NAType"):
return None
if isinstance(val, (datetime.datetime, datetime.date, datetime.time, datetime.timedelta)):
return val
to_pydt = getattr(val, "to_pydatetime", None)
if callable(to_pydt):
try:
dt = to_pydt()
if isinstance(dt, (datetime.datetime, datetime.date)):
return dt
except (ValueError, TypeError):
pass
to_pytd = getattr(val, "to_pytimedelta", None)
if callable(to_pytd):
try:
td = to_pytd()
if isinstance(td, datetime.timedelta):
return td
except (ValueError, TypeError):
pass
kind = getattr(getattr(val, "dtype", None), "kind", None)
if kind in ("M", "m"):
item_fn = getattr(val, "item", None)
if callable(item_fn):
try:
item = item_fn()
if item is None:
return None
if isinstance(item, (datetime.datetime, datetime.date, datetime.timedelta)):
return item
except (ValueError, TypeError, OverflowError):
pass
text = str(val)
return None if text in ("NaT", "NaTType") else text
return val
def to_calc_compatible(val: Any) -> float | str | tuple[Any, ...]:
"""Recursively convert Python values into LibreOffice Calc supported types.
Calc cells and matrix formulas only support float (UNO double) and str (UNO string).
Crucially, Calc matrix formulas do NOT support integer (UNO long) types and will
throw #VALUE! if a sequence contains integers/longs. Python booleans are converted
to 1.0 / 0.0 (UNO double) because Calc's Add-In bridge only unpacks doubles and strings.
Host LibreOffice Python has no pandas/numpy — temporal pandas types are duck-typed
(Timestamp subclasses datetime; NaT is NaTType). Do not import pandas here.
"""
val = to_stdlib_temporal(val)
if val is None:
return ""
# ScUnoAddInCall unpacks only double and string; map bool to 1.0/0.0 so logical formulas work.
if isinstance(val, bool):
return 1.0 if val else 0.0
# Integers beyond float64 range return str(val) instead of raising OverflowError.
if isinstance(val, int):
try:
return float(val)
except OverflowError:
return str(val)
if isinstance(val, float):
# Computed NaN (or NaN from a numeric grid that contained blanks) is returned as-is.
# The Calc add-in bridge renders a raw NaN double as a cascading error (#NUM! or #VALUE!).
# Python None is mapped to "" (empty cell). We intentionally do NOT collapse NaN here.
# ±inf is returned as-is too; the add-in bridge shows it as #NUM! (GetDoubleErrorValue).
return val
if isinstance(val, str):
return val
if isinstance(val, datetime.datetime):
return _calc_iso_datetime(val)
if isinstance(val, datetime.date):
return val.isoformat()
if isinstance(val, datetime.time):
return val.isoformat()
if isinstance(val, datetime.timedelta):
# In Calc, time intervals are represented as fractional days (e.g. 1.0 = 24 hours)
return val.total_seconds() / 86400.0
if hasattr(val, "__float__") and not isinstance(val, (bytes, list, tuple, dict, set)):
try:
return float(val) # type: ignore[arg-type]
except (ValueError, TypeError, OverflowError):
pass
if isinstance(val, (list, tuple)):
if not val:
return ()
# Check if 2D sequence (contains nested rows)
if any(isinstance(row, (list, tuple)) for row in val):
# Normalize each row to a list of elements
rows: list[list[Any]] = [list(row) if isinstance(row, (list, tuple)) else [row] for row in val]
max_cols = max(len(row) for row in rows)
# Rectangularize by padding shorter rows with "" so Calc matrix receives a valid rectangular grid
padded_rows = []
for row in rows:
padded = [to_calc_compatible(cell) for cell in row]
if len(padded) < max_cols:
padded.extend([""] * (max_cols - len(padded)))
padded_rows.append(tuple(padded))
return tuple(padded_rows)
return tuple(to_calc_compatible(item) for item in val)
return str(val)
def flatten_result_values(result: Any) -> list[Any]:
"""Row-major flattening for list / nested list worker results."""
if not isinstance(result, (list, tuple)):
return [result]
return [cell for row in result_as_spill_grid(result) for cell in row]
def result_as_spill_grid(result: list[Any] | tuple[Any, ...]) -> list[list[Any]]:
"""Normalize a 1D list or 2D list-of-lists into a rectangular spill grid."""
if not result:
return []
if any(isinstance(row, (list, tuple)) for row in result):
return [list(row) if isinstance(row, (list, tuple)) else [row] for row in result]
return [[x] for x in result]
@dataclass(frozen=True, slots=True)
class SpillValue:
"""One =PY() spill neighbour, classified once.
calc_value is what setDataArray receives (float, str, or None for #N/A void).
kind is "n" number, "s" text, "e" empty, "err" formula error; the spill writer uses it to pick
setDataArray versus an error formula and to skip temporal formats.
temporal_category is "date" / "time" / "datetime" / "duration" when calc_value is a day
serial that should get a number format; None otherwise. error_code is the Calc
FormulaError when kind == "err".
"""
calc_value: Any
kind: str
temporal_category: str | None = None
error_code: int | None = None
_SPILL_EMPTY = SpillValue("", "e")
def _spill_error(code: int) -> SpillValue:
# A NaN written via SetValue becomes a plain numeric cell with ISERROR 0 and
# reloads from ODS as 0. setDataArray of None maps in PyUNO to UNO void, which
# Calc's lcl_PutDataArray handles via SetError(NotAvailable) for #N/A;
# #ERR32767! is not a published constant so we cannot use setFormula for #N/A.
# For other codes, "" serves as an empty placeholder in setDataArray and
# perform_deferred_spill assigns the formula f"=#ERR{code}!".
return SpillValue(None if code == ERR_NA else "", "err", error_code=code)
def _spill_from_calc(calc_val: Any) -> SpillValue:
if isinstance(calc_val, float):
if not math.isfinite(calc_val):
return _spill_error(nonfinite_error_code(calc_val))
return SpillValue(calc_val, "n")
if isinstance(calc_val, str):
return SpillValue(calc_val, "s")
return SpillValue(calc_val, "e")
def coerce_spill_value(val: Any, null_dt: datetime.date = datetime.date(1899, 12, 30)) -> SpillValue:
"""Classify one raw grid cell value into a ``SpillValue`` record."""
val = to_stdlib_temporal(val)
if val is None:
return _SPILL_EMPTY
if isinstance(val, (int, float)):
# bool is an int. to_calc_compatible maps it to 1.0/0.0 and OverflowError to decimal text.
return _spill_from_calc(to_calc_compatible(val))
if isinstance(val, datetime.datetime):
return SpillValue(datetime_serial(_naive_datetime(val), null_dt), "n", "datetime")
if isinstance(val, datetime.date):
return SpillValue(datetime_serial(val, null_dt), "n", "date")
if isinstance(val, datetime.time):
return SpillValue(time_day_fraction(val), "n", "time")
if isinstance(val, datetime.timedelta):
return SpillValue(val.total_seconds() / 86400.0, "n", "duration")
if isinstance(val, str):
stripped = val.strip()
if not stripped:
return _SPILL_EMPTY
err = calc_error_code_for_token(stripped)
if err is not None:
return _spill_error(err)
if match_iso_duration(stripped):
try:
return SpillValue(duration_serial_from_iso(stripped), "n", "duration")
except (ValueError, OverflowError):
pass
cat = match_iso_temporal(stripped)
if cat is not None:
try:
if cat == "date":
parsed: datetime.date | datetime.datetime | datetime.time = datetime.date.fromisoformat(stripped)
elif cat == "datetime":
parsed = datetime.datetime.fromisoformat(stripped.replace(" ", "T"))
else:
parsed = datetime.time.fromisoformat(stripped)
return coerce_spill_value(parsed, null_dt)
except ValueError:
pass
return SpillValue(val, "s")
return _spill_from_calc(to_calc_compatible(val))
def format_addin_error_for_display(exc: BaseException) -> str:
"""Cell text for an exception raised while running =PY()."""
# A TimeoutError here is the host's main-thread marshal or sync timeout, not the user's code or an HTTP request, so it gets its own message.
if isinstance(exc, TimeoutError):
return _main_thread_timeout_template().format(str(exc))
return _error_cell_text(format_error_message(exc))
def _error_cell_text(message: str) -> str:
"""Ensure an error cell message starts with ``Error:`` or ``#``."""
text = message.strip() or _("Unknown error")
if text.startswith(("Error:", "#")):
return text
return _error_text_template().format(text)