pyo3 0.28.3

Bindings to Python interpreter
Documentation
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//! Runtime inspection of objects exposed to Python.
//!
//! Tracking issue: <https://github.com/PyO3/pyo3/issues/2454>.

use std::fmt::{self, Display, Write};

pub mod types;

/// Builds a type hint from a module name and a member name in the module
///
/// ```
/// use pyo3::type_hint_identifier;
/// use pyo3::inspect::PyStaticExpr;
///
/// const T: PyStaticExpr = type_hint_identifier!("datetime", "date");
/// assert_eq!(T.to_string(), "datetime.date");
///
/// const T2: PyStaticExpr = type_hint_identifier!("builtins", "int");
/// assert_eq!(T2.to_string(), "int");
/// ```
#[macro_export]
macro_rules! type_hint_identifier {
    ("builtins", $name:expr) => {
        $crate::inspect::PyStaticExpr::Name { id: $name }
    };
    ($module:expr, $name:expr) => {
        $crate::inspect::PyStaticExpr::Attribute {
            value: &$crate::inspect::PyStaticExpr::Name { id: $module },
            attr: $name,
        }
    };
}
pub(crate) use type_hint_identifier;

/// Builds the union of multiple type hints
///
/// ```
/// use pyo3::{type_hint_identifier, type_hint_union};
/// use pyo3::inspect::PyStaticExpr;
///
/// const T: PyStaticExpr = type_hint_union!(type_hint_identifier!("builtins", "int"), type_hint_identifier!("builtins", "float"));
/// assert_eq!(T.to_string(), "int | float");
/// ```
#[macro_export]
macro_rules! type_hint_union {
    ($e:expr) => { $e };
    ($l:expr , $($r:expr),+) => { $crate::inspect::PyStaticExpr::BinOp {
        left: &$l,
        op: $crate::inspect::PyStaticOperator::BitOr,
        right: &type_hint_union!($($r),+),
    } };
}
pub(crate) use type_hint_union;

/// Builds a subscribed type hint
///
/// ```
/// use pyo3::{type_hint_identifier, type_hint_subscript};
/// use pyo3::inspect::PyStaticExpr;
///
/// const T: PyStaticExpr = type_hint_subscript!(type_hint_identifier!("collections.abc", "Sequence"), type_hint_identifier!("builtins", "float"));
/// assert_eq!(T.to_string(), "collections.abc.Sequence[float]");
///
/// const T2: PyStaticExpr = type_hint_subscript!(type_hint_identifier!("builtins", "dict"), type_hint_identifier!("builtins", "str"), type_hint_identifier!("builtins", "float"));
/// assert_eq!(T2.to_string(), "dict[str, float]");
/// ```
#[macro_export]
macro_rules! type_hint_subscript {
    ($l:expr, $r:expr) => {
        $crate::inspect::PyStaticExpr::Subscript {
            value: &$l,
            slice: &$r
        }
    };
    ($l:expr, $($r:expr),*) => {
        $crate::inspect::PyStaticExpr::Subscript {
            value: &$l,
            slice: &$crate::inspect::PyStaticExpr::Tuple { elts: &[$($r),*] }
        }
    };
}
pub(crate) use type_hint_subscript;

/// A Python expression.
///
/// This is the `expr` production of the [Python `ast` module grammar](https://docs.python.org/3/library/ast.html#abstract-grammar)
///
/// This struct aims at being used in `const` contexts like in [`FromPyObject::INPUT_TYPE`](crate::FromPyObject::INPUT_TYPE) and [`IntoPyObject::OUTPUT_TYPE`](crate::IntoPyObject::OUTPUT_TYPE).
///
/// Use macros like [`type_hint_identifier`], [`type_hint_union`] and [`type_hint_subscript`] to construct values.
#[derive(Clone, Copy)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum PyStaticExpr {
    /// A constant like `None` or `123`
    Constant { value: PyStaticConstant },
    /// A name
    Name { id: &'static str },
    /// An attribute `value.attr`
    Attribute {
        value: &'static Self,
        attr: &'static str,
    },
    /// A binary operator
    BinOp {
        left: &'static Self,
        op: PyStaticOperator,
        right: &'static Self,
    },
    /// A tuple
    Tuple { elts: &'static [Self] },
    /// A list
    List { elts: &'static [Self] },
    /// A subscript `value[slice]`
    Subscript {
        value: &'static Self,
        slice: &'static Self,
    },
    /// A `#[pyclass]` type. This is separated type for introspection reasons.
    PyClass(PyClassNameStaticExpr),
}

/// Serialize the type for introspection and return the number of written bytes
#[doc(hidden)]
pub const fn serialize_for_introspection(expr: &PyStaticExpr, mut output: &mut [u8]) -> usize {
    let original_len = output.len();
    match expr {
        PyStaticExpr::Constant { value } => match value {
            PyStaticConstant::None => {
                output = write_slice_and_move_forward(
                    b"{\"type\":\"constant\",\"kind\":\"none\"}",
                    output,
                )
            }
            PyStaticConstant::Bool(value) => {
                output = write_slice_and_move_forward(
                    if *value {
                        b"{\"type\":\"constant\",\"kind\":\"bool\",\"value\":true}"
                    } else {
                        b"{\"type\":\"constant\",\"kind\":\"bool\",\"value\":false}"
                    },
                    output,
                )
            }
            PyStaticConstant::Int(value) => {
                output = write_slice_and_move_forward(
                    b"{\"type\":\"constant\",\"kind\":\"int\",\"value\":\"",
                    output,
                );
                output = write_slice_and_move_forward(value.as_bytes(), output);
                output = write_slice_and_move_forward(b"\"}", output);
            }
            PyStaticConstant::Float(value) => {
                output = write_slice_and_move_forward(
                    b"{\"type\":\"constant\",\"kind\":\"float\",\"value\":\"",
                    output,
                );
                output = write_slice_and_move_forward(value.as_bytes(), output);
                output = write_slice_and_move_forward(b"\"}", output);
            }
            PyStaticConstant::Str(value) => {
                output = write_slice_and_move_forward(
                    b"{\"type\":\"constant\",\"kind\":\"str\",\"value\":",
                    output,
                );
                output = write_json_string_and_move_forward(value.as_bytes(), output);
                output = write_slice_and_move_forward(b"}", output);
            }
            PyStaticConstant::Ellipsis => {
                output = write_slice_and_move_forward(
                    b"{\"type\":\"constant\",\"kind\":\"ellipsis\"}",
                    output,
                )
            }
        },
        PyStaticExpr::Name { id } => {
            output = write_slice_and_move_forward(b"{\"type\":\"name\",\"id\":\"", output);
            output = write_slice_and_move_forward(id.as_bytes(), output);
            output = write_slice_and_move_forward(b"\"}", output);
        }
        PyStaticExpr::Attribute { value, attr } => {
            output = write_slice_and_move_forward(b"{\"type\":\"attribute\",\"value\":", output);
            output = write_expr_and_move_forward(value, output);
            output = write_slice_and_move_forward(b",\"attr\":\"", output);
            output = write_slice_and_move_forward(attr.as_bytes(), output);
            output = write_slice_and_move_forward(b"\"}", output);
        }
        PyStaticExpr::BinOp { left, op, right } => {
            output = write_slice_and_move_forward(b"{\"type\":\"binop\",\"left\":", output);
            output = write_expr_and_move_forward(left, output);
            output = write_slice_and_move_forward(b",\"op\":\"", output);
            output = write_slice_and_move_forward(
                match op {
                    PyStaticOperator::BitOr => b"bitor",
                },
                output,
            );
            output = write_slice_and_move_forward(b"\",\"right\":", output);
            output = write_expr_and_move_forward(right, output);
            output = write_slice_and_move_forward(b"}", output);
        }
        PyStaticExpr::Tuple { elts } => {
            output = write_container_and_move_forward(b"tuple", elts, output);
        }
        PyStaticExpr::List { elts } => {
            output = write_container_and_move_forward(b"list", elts, output);
        }
        PyStaticExpr::Subscript { value, slice } => {
            output = write_slice_and_move_forward(b"{\"type\":\"subscript\",\"value\":", output);
            output = write_expr_and_move_forward(value, output);
            output = write_slice_and_move_forward(b",\"slice\":", output);
            output = write_expr_and_move_forward(slice, output);
            output = write_slice_and_move_forward(b"}", output);
        }
        PyStaticExpr::PyClass(expr) => {
            output = write_slice_and_move_forward(b"{\"type\":\"id\",\"id\":\"", output);
            output = write_slice_and_move_forward(expr.introspection_id.as_bytes(), output);
            output = write_slice_and_move_forward(b"\"}", output);
        }
    }
    original_len - output.len()
}

/// Length required by [`serialize_for_introspection`]
#[doc(hidden)]
pub const fn serialized_len_for_introspection(expr: &PyStaticExpr) -> usize {
    match expr {
        PyStaticExpr::Constant { value } => match value {
            PyStaticConstant::None => 33,
            PyStaticConstant::Bool(value) => 42 + if *value { 4 } else { 5 },
            PyStaticConstant::Int(value) => 43 + value.len(),
            PyStaticConstant::Float(value) => 45 + value.len(),
            PyStaticConstant::Str(value) => 41 + serialized_json_string_len(value),
            PyStaticConstant::Ellipsis => 37,
        },
        PyStaticExpr::Name { id } => 23 + id.len(),
        PyStaticExpr::Attribute { value, attr } => {
            39 + serialized_len_for_introspection(value) + attr.len()
        }
        PyStaticExpr::BinOp { left, op, right } => {
            41 + serialized_len_for_introspection(left)
                + match op {
                    PyStaticOperator::BitOr => 5,
                }
                + serialized_len_for_introspection(right)
        }
        PyStaticExpr::Tuple { elts } => 5 + serialized_container_len_for_introspection(elts),
        PyStaticExpr::List { elts } => 4 + serialized_container_len_for_introspection(elts),
        PyStaticExpr::Subscript { value, slice } => {
            38 + serialized_len_for_introspection(value) + serialized_len_for_introspection(slice)
        }
        PyStaticExpr::PyClass(expr) => 21 + expr.introspection_id.len(),
    }
}

impl fmt::Display for PyStaticExpr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Constant { value } => match value {
                PyStaticConstant::None => f.write_str("None"),
                PyStaticConstant::Bool(value) => f.write_str(if *value { "True" } else { "False" }),
                PyStaticConstant::Int(value) => f.write_str(value),
                PyStaticConstant::Float(value) => {
                    f.write_str(value)?;
                    if !value.contains(['.', 'e', 'E']) {
                        // Makes sure it's not parsed as an int
                        f.write_char('.')?;
                    }
                    Ok(())
                }
                PyStaticConstant::Str(value) => write!(f, "{value:?}"),
                PyStaticConstant::Ellipsis => f.write_str("..."),
            },
            Self::Name { id, .. } => f.write_str(id),
            Self::Attribute { value, attr } => {
                value.fmt(f)?;
                f.write_str(".")?;
                f.write_str(attr)
            }
            Self::BinOp { left, op, right } => {
                left.fmt(f)?;
                f.write_char(' ')?;
                f.write_char(match op {
                    PyStaticOperator::BitOr => '|',
                })?;
                f.write_char(' ')?;
                right.fmt(f)
            }
            Self::Tuple { elts } => {
                f.write_char('(')?;
                fmt_elements(elts, f)?;
                if elts.len() == 1 {
                    f.write_char(',')?;
                }
                f.write_char(')')
            }
            Self::List { elts } => {
                f.write_char('[')?;
                fmt_elements(elts, f)?;
                f.write_char(']')
            }
            Self::Subscript { value, slice } => {
                value.fmt(f)?;
                f.write_char('[')?;
                if let PyStaticExpr::Tuple { elts } = slice {
                    // We don't display the tuple parentheses
                    fmt_elements(elts, f)?;
                } else {
                    slice.fmt(f)?;
                }
                f.write_char(']')
            }
            Self::PyClass(expr) => expr.expr.fmt(f),
        }
    }
}

/// A PyO3 extension to the Python AST to know more about [`PyStaticExpr::Constant`].
///
/// This enables advanced features like escaping.
#[derive(Clone, Copy)]
#[non_exhaustive]
pub enum PyStaticConstant {
    /// None
    None,
    /// The `True` and `False` booleans
    Bool(bool),
    /// `int` value written in base 10 (`[+-]?[0-9]+`)
    Int(&'static str),
    /// `float` value written in base-10 (`[+-]?[0-9]*(.[0-9]*)*([eE])[0-9]*`), not including Inf and NaN
    Float(&'static str),
    /// `str` value unescaped and without quotes
    Str(&'static str),
    /// `...` value
    Ellipsis,
}

/// An operator used in [`PyStaticExpr::BinOp`].
#[derive(Clone, Copy)]
#[non_exhaustive]
pub enum PyStaticOperator {
    /// `|` operator
    BitOr,
}

const fn write_slice_and_move_forward<'a>(value: &[u8], output: &'a mut [u8]) -> &'a mut [u8] {
    // TODO: use copy_from_slice with MSRV 1.87+
    let mut i = 0;
    while i < value.len() {
        output[i] = value[i];
        i += 1;
    }
    output.split_at_mut(value.len()).1
}

const fn write_json_string_and_move_forward<'a>(
    value: &[u8],
    output: &'a mut [u8],
) -> &'a mut [u8] {
    let mut input_i = 0;
    let mut output_i = 0;
    output[output_i] = b'"';
    output_i += 1;
    while input_i < value.len() {
        match value[input_i] {
            b'\\' => {
                output[output_i] = b'\\';
                output_i += 1;
                output[output_i] = b'\\';
                output_i += 1;
            }
            b'"' => {
                output[output_i] = b'\\';
                output_i += 1;
                output[output_i] = b'"';
                output_i += 1;
            }
            0x08 => {
                output[output_i] = b'\\';
                output_i += 1;
                output[output_i] = b'b';
                output_i += 1;
            }
            0x0C => {
                output[output_i] = b'\\';
                output_i += 1;
                output[output_i] = b'f';
                output_i += 1;
            }
            b'\n' => {
                output[output_i] = b'\\';
                output_i += 1;
                output[output_i] = b'n';
                output_i += 1;
            }
            b'\r' => {
                output[output_i] = b'\\';
                output_i += 1;
                output[output_i] = b'r';
                output_i += 1;
            }
            b'\t' => {
                output[output_i] = b'\\';
                output_i += 1;
                output[output_i] = b't';
                output_i += 1;
            }
            c @ 0..32 => {
                output[output_i] = b'\\';
                output_i += 1;
                output[output_i] = b'u';
                output_i += 1;
                output[output_i] = b'0';
                output_i += 1;
                output[output_i] = b'0';
                output_i += 1;
                output[output_i] = b'0' + (c / 16);
                output_i += 1;
                let remainer = c % 16;
                output[output_i] = if remainer >= 10 {
                    b'A' + remainer - 10
                } else {
                    b'0' + remainer
                };
                output_i += 1;
            }
            c => {
                output[output_i] = c;
                output_i += 1;
            }
        }
        input_i += 1;
    }
    output[output_i] = b'"';
    output_i += 1;
    output.split_at_mut(output_i).1
}

const fn write_expr_and_move_forward<'a>(
    value: &PyStaticExpr,
    output: &'a mut [u8],
) -> &'a mut [u8] {
    let written = serialize_for_introspection(value, output);
    output.split_at_mut(written).1
}

const fn write_container_and_move_forward<'a>(
    name: &'static [u8],
    elts: &[PyStaticExpr],
    mut output: &'a mut [u8],
) -> &'a mut [u8] {
    output = write_slice_and_move_forward(b"{\"type\":\"", output);
    output = write_slice_and_move_forward(name, output);
    output = write_slice_and_move_forward(b"\",\"elts\":[", output);
    let mut i = 0;
    while i < elts.len() {
        if i > 0 {
            output = write_slice_and_move_forward(b",", output);
        }
        output = write_expr_and_move_forward(&elts[i], output);
        i += 1;
    }
    write_slice_and_move_forward(b"]}", output)
}

const fn serialized_container_len_for_introspection(elts: &[PyStaticExpr]) -> usize {
    let mut len = 21;
    let mut i = 0;
    while i < elts.len() {
        if i > 0 {
            len += 1;
        }
        len += serialized_len_for_introspection(&elts[i]);
        i += 1;
    }
    len
}

const fn serialized_json_string_len(value: &str) -> usize {
    let value = value.as_bytes();
    let mut len = 2;
    let mut i = 0;
    while i < value.len() {
        len += match value[i] {
            b'\\' | b'"' | 0x08 | 0x0C | b'\n' | b'\r' | b'\t' => 2,
            0..32 => 6,
            _ => 1,
        };
        i += 1;
    }
    len
}

fn fmt_elements(elts: &[PyStaticExpr], f: &mut fmt::Formatter<'_>) -> fmt::Result {
    for (i, elt) in elts.iter().enumerate() {
        if i > 0 {
            f.write_str(", ")?;
        }
        elt.fmt(f)?;
    }
    Ok(())
}

/// The full name of a `#[pyclass]` inside a [`PyStaticExpr`].
///
/// To get the underlying [`PyStaticExpr`] use [`expr`](PyClassNameStaticExpr::expr).
#[derive(Clone, Copy)]
pub struct PyClassNameStaticExpr {
    expr: &'static PyStaticExpr,
    introspection_id: &'static str,
}

impl PyClassNameStaticExpr {
    #[doc(hidden)]
    #[inline]
    pub const fn new(expr: &'static PyStaticExpr, introspection_id: &'static str) -> Self {
        Self {
            expr,
            introspection_id,
        }
    }

    /// The pyclass type as an expression like `module.name`
    ///
    /// This is based on the `name` and `module` parameter of the `#[pyclass]` macro.
    /// The `module` part might not be a valid module from which the type can be imported.
    #[inline]
    pub const fn expr(&self) -> &'static PyStaticExpr {
        self.expr
    }
}

impl AsRef<PyStaticExpr> for PyClassNameStaticExpr {
    #[inline]
    fn as_ref(&self) -> &PyStaticExpr {
        self.expr
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_to_string() {
        const T: PyStaticExpr = type_hint_subscript!(
            type_hint_identifier!("builtins", "dict"),
            type_hint_union!(
                type_hint_identifier!("builtins", "int"),
                type_hint_subscript!(
                    type_hint_identifier!("typing", "Literal"),
                    PyStaticExpr::Constant {
                        value: PyStaticConstant::Str("\0\t\\\"")
                    }
                )
            ),
            type_hint_identifier!("datetime", "time")
        );
        assert_eq!(
            T.to_string(),
            "dict[int | typing.Literal[\"\\0\\t\\\\\\\"\"], datetime.time]"
        )
    }

    #[test]
    fn test_serialize_for_introspection() {
        fn check_serialization(expr: PyStaticExpr, expected: &str) {
            let mut out = vec![0; serialized_len_for_introspection(&expr)];
            serialize_for_introspection(&expr, &mut out);
            assert_eq!(std::str::from_utf8(&out).unwrap(), expected)
        }

        check_serialization(
            PyStaticExpr::Constant {
                value: PyStaticConstant::None,
            },
            r#"{"type":"constant","kind":"none"}"#,
        );
        check_serialization(
            type_hint_identifier!("builtins", "int"),
            r#"{"type":"name","id":"int"}"#,
        );
        check_serialization(
            type_hint_identifier!("datetime", "date"),
            r#"{"type":"attribute","value":{"type":"name","id":"datetime"},"attr":"date"}"#,
        );
        check_serialization(
            type_hint_union!(
                type_hint_identifier!("builtins", "int"),
                type_hint_identifier!("builtins", "float")
            ),
            r#"{"type":"binop","left":{"type":"name","id":"int"},"op":"bitor","right":{"type":"name","id":"float"}}"#,
        );
        check_serialization(
            PyStaticExpr::Tuple {
                elts: &[type_hint_identifier!("builtins", "list")],
            },
            r#"{"type":"tuple","elts":[{"type":"name","id":"list"}]}"#,
        );
        check_serialization(
            PyStaticExpr::List {
                elts: &[type_hint_identifier!("builtins", "list")],
            },
            r#"{"type":"list","elts":[{"type":"name","id":"list"}]}"#,
        );
        check_serialization(
            type_hint_subscript!(
                type_hint_identifier!("builtins", "list"),
                type_hint_identifier!("builtins", "int")
            ),
            r#"{"type":"subscript","value":{"type":"name","id":"list"},"slice":{"type":"name","id":"int"}}"#,
        );
        check_serialization(
            PyStaticExpr::PyClass(PyClassNameStaticExpr::new(
                &type_hint_identifier!("builtins", "foo"),
                "foo",
            )),
            r#"{"type":"id","id":"foo"}"#,
        );
        check_serialization(
            PyStaticExpr::Constant {
                value: PyStaticConstant::Bool(true),
            },
            r#"{"type":"constant","kind":"bool","value":true}"#,
        );
        check_serialization(
            PyStaticExpr::Constant {
                value: PyStaticConstant::Bool(false),
            },
            r#"{"type":"constant","kind":"bool","value":false}"#,
        );
        check_serialization(
            PyStaticExpr::Constant {
                value: PyStaticConstant::Int("-123"),
            },
            r#"{"type":"constant","kind":"int","value":"-123"}"#,
        );
        check_serialization(
            PyStaticExpr::Constant {
                value: PyStaticConstant::Float("-2.1"),
            },
            r#"{"type":"constant","kind":"float","value":"-2.1"}"#,
        );
        check_serialization(
            PyStaticExpr::Constant {
                value: PyStaticConstant::Float("+2.1e10"),
            },
            r#"{"type":"constant","kind":"float","value":"+2.1e10"}"#,
        );
        check_serialization(
            PyStaticExpr::Constant {
                value: PyStaticConstant::Str("abc(1)"),
            },
            r#"{"type":"constant","kind":"str","value":"abc(1)"}"#,
        );
        check_serialization(
            PyStaticExpr::Constant {
                value: PyStaticConstant::Str("\"\\/\x08\x0C\n\r\t\0\x19a"),
            },
            r#"{"type":"constant","kind":"str","value":"\"\\/\b\f\n\r\t\u0000\u0019a"}"#,
        );
        check_serialization(
            PyStaticExpr::Constant {
                value: PyStaticConstant::Ellipsis,
            },
            r#"{"type":"constant","kind":"ellipsis"}"#,
        );
    }
}