from pathlib import Path
import sys
import tempfile
+import textwrap
import unittest
from test import support
+from test.support.script_helper import assert_python_ok
from . import tomllib
never imported by tests.
"""
importlib.import_module(f"{tomllib.__name__}._types")
+
+ def test_lazy_import(self):
+ # Test the TOML file can be parsed without importing regular
+ # expressions (tomllib._re)
+ code = textwrap.dedent("""
+ import sys, tomllib, textwrap
+ document = textwrap.dedent('''
+ [metadata]
+ key = "text"
+ array = ["array", "of", "text"]
+ booleans = [true, false]
+ ''')
+ tomllib.loads(document)
+ print("lazy import?", 'tomllib._re' not in sys.modules)
+ """)
+ proc = assert_python_ok("-c", code)
+ self.assertIn(b"lazy import? True", proc.out)
from __future__ import annotations
-from types import MappingProxyType
+# Defer loading regular expressions until we actually need them in
+# parse_value().
+__lazy_modules__ = ["tomllib._re"]
+
+import sys
from ._re import (
RE_DATETIME,
match_to_number,
)
+if sys.version_info < (3, 15):
+ from types import MappingProxyType as frozendict
+
TYPE_CHECKING = False
if TYPE_CHECKING:
from collections.abc import Iterable
KEY_INITIAL_CHARS: Final = BARE_KEY_CHARS | frozenset("\"'")
HEXDIGIT_CHARS: Final = frozenset("abcdef" "ABCDEF" "0123456789")
-BASIC_STR_ESCAPE_REPLACEMENTS: Final = MappingProxyType(
+BASIC_STR_ESCAPE_REPLACEMENTS: Final = frozendict(
{
"\\b": "\u0008", # backspace
"\\t": "\u0009", # tab