MCPcopy Create free account
hub / github.com/deepnote/deepnote / toPythonLiteral

Function toPythonLiteral

packages/runtime-core/src/javascript.ts:4–40  ·  view source on GitHub ↗
(value: unknown)

Source from the content-addressed store, hash-verified

2 * Convert a JavaScript value to a Python literal.
3 */
4export function toPythonLiteral(value: unknown): string {
5 if (value === null || value === undefined) {
6 return 'None'
7 }
8 if (typeof value === 'boolean') {
9 return value ? 'True' : 'False'
10 }
11 if (typeof value === 'number') {
12 if (!Number.isFinite(value)) {
13 throw new Error(`Cannot convert non-finite number to Python: ${value}`)
14 }
15 return String(value)
16 }
17 if (typeof value === 'string') {
18 // Escape for Python string literal
19 const escaped = value
20 .replace(/\\/g, '\\\\')
21 .replace(/'/g, "\\'")
22 .replace(/\n/g, '\\n')
23 .replace(/\r/g, '\\r')
24 .replace(/\t/g, '\\t')
25 .replace(/\0/g, '\\x00')
26 // Escape other control characters (code points < 0x20 except already handled, and DEL 0x7F)
27 // biome-ignore lint/suspicious/noControlCharactersInRegex: intentionally escaping control chars
28 .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, char => `\\x${char.charCodeAt(0).toString(16).padStart(2, '0')}`)
29 return `'${escaped}'`
30 }
31 if (Array.isArray(value)) {
32 const elements = value.map(v => toPythonLiteral(v))
33 return `[${elements.join(', ')}]`
34 }
35 if (typeof value === 'object') {
36 const entries = Object.entries(value).map(([k, v]) => `${toPythonLiteral(k)}: ${toPythonLiteral(v)}`)
37 return `{${entries.join(', ')}}`
38 }
39 throw new Error(`Cannot convert value of type ${typeof value} to Python literal`)
40}

Callers 2

javascript.test.tsFile · 0.90
injectInputsMethod · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected