Skip to content

Commit 329e049

Browse files
committed
tomllib: Sync with Tomli to reduce diff
1 parent 2199c58 commit 329e049

File tree

4 files changed

+37
-71
lines changed

4 files changed

+37
-71
lines changed

Lib/test/test_tomllib/burntsushi.py

Lines changed: 8 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,8 @@
77
import datetime
88
from typing import Any
99

10-
# Aliases for converting TOML compliance format [1] to BurntSushi format [2]
11-
# [1] https://github.com/toml-lang/compliance/blob/db7c3211fda30ff9ddb10292f4aeda7e2e10abc4/docs/json-encoding.md # noqa: E501
12-
# [2] https://github.com/BurntSushi/toml-test/blob/4634fdf3a6ecd6aaea5f4cdcd98b2733c2694993/README.md # noqa: E501
13-
_aliases = {
14-
"boolean": "bool",
15-
"offset datetime": "datetime",
16-
"local datetime": "datetime-local",
17-
"local date": "date-local",
18-
"local time": "time-local",
19-
}
20-
21-
22-
def convert(obj): # noqa: C901
10+
11+
def convert(obj):
2312
if isinstance(obj, str):
2413
return {"type": "string", "value": obj}
2514
elif isinstance(obj, bool):
@@ -53,31 +42,25 @@ def convert(obj): # noqa: C901
5342
def normalize(obj: Any) -> Any:
5443
"""Normalize test objects.
5544
56-
This normalizes primitive values (e.g. floats), and also converts from
57-
TOML compliance format [1] to BurntSushi format [2].
58-
59-
[1] https://github.com/toml-lang/compliance/blob/db7c3211fda30ff9ddb10292f4aeda7e2e10abc4/docs/json-encoding.md # noqa: E501
60-
[2] https://github.com/BurntSushi/toml-test/blob/4634fdf3a6ecd6aaea5f4cdcd98b2733c2694993/README.md # noqa: E501
61-
"""
45+
This normalizes primitive values (e.g. floats)."""
6246
if isinstance(obj, list):
6347
return [normalize(item) for item in obj]
6448
if isinstance(obj, dict):
6549
if "type" in obj and "value" in obj:
6650
type_ = obj["type"]
67-
norm_type = _aliases.get(type_, type_)
6851
value = obj["value"]
69-
if norm_type == "float":
52+
if type_ == "float":
7053
norm_value = _normalize_float_str(value)
71-
elif norm_type in {"datetime", "datetime-local"}:
54+
elif type_ in {"datetime", "datetime-local"}:
7255
norm_value = _normalize_datetime_str(value)
73-
elif norm_type == "time-local":
56+
elif type_ == "time-local":
7457
norm_value = _normalize_localtime_str(value)
7558
else:
7659
norm_value = value
7760

78-
if norm_type == "array":
61+
if type_ == "array":
7962
return [normalize(item) for item in value]
80-
return {"type": norm_type, "value": norm_value}
63+
return {"type": type_, "value": norm_value}
8164
return {k: normalize(v) for k, v in obj.items()}
8265
raise AssertionError("Burntsushi fixtures should be dicts/lists only")
8366

Lib/test/test_tomllib/test_data.py

Lines changed: 1 addition & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,6 @@
88

99
from . import burntsushi, tomllib
1010

11-
12-
class MissingFile:
13-
def __init__(self, path: Path):
14-
self.path = path
15-
16-
1711
DATA_DIR = Path(__file__).parent / "data"
1812

1913
VALID_FILES = tuple((DATA_DIR / "valid").glob("**/*.toml"))
@@ -22,10 +16,7 @@ def __init__(self, path: Path):
2216
_expected_files = []
2317
for p in VALID_FILES:
2418
json_path = p.with_suffix(".json")
25-
try:
26-
text = json.loads(json_path.read_bytes().decode())
27-
except FileNotFoundError:
28-
text = MissingFile(json_path)
19+
text = json.loads(json_path.read_bytes().decode())
2920
_expected_files.append(text)
3021
VALID_FILES_EXPECTED = tuple(_expected_files)
3122

@@ -49,14 +40,6 @@ def test_invalid(self):
4940
def test_valid(self):
5041
for valid, expected in zip(VALID_FILES, VALID_FILES_EXPECTED):
5142
with self.subTest(msg=valid.stem):
52-
if isinstance(expected, MissingFile):
53-
# For a poor man's xfail, assert that this is one of the
54-
# test cases where expected data is known to be missing.
55-
assert valid.stem in {
56-
"qa-array-inline-nested-1000",
57-
"qa-table-inline-nested-1000",
58-
}
59-
continue
6043
toml_str = valid.read_bytes().decode()
6144
actual = tomllib.loads(toml_str)
6245
actual = burntsushi.convert(actual)

Lib/tomllib/_parser.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -18,40 +18,40 @@
1818
TYPE_CHECKING = False
1919
if TYPE_CHECKING:
2020
from collections.abc import Iterable
21-
from typing import IO, Any
21+
from typing import IO, Any, Final
2222

2323
from ._types import Key, ParseFloat, Pos
2424

25-
ASCII_CTRL = frozenset(chr(i) for i in range(32)) | frozenset(chr(127))
25+
ASCII_CTRL: Final = frozenset(chr(i) for i in range(32)) | frozenset(chr(127))
2626

2727
# Neither of these sets include quotation mark or backslash. They are
2828
# currently handled as separate cases in the parser functions.
29-
ILLEGAL_BASIC_STR_CHARS = ASCII_CTRL - frozenset("\t")
30-
ILLEGAL_MULTILINE_BASIC_STR_CHARS = ASCII_CTRL - frozenset("\t\n")
29+
ILLEGAL_BASIC_STR_CHARS: Final = ASCII_CTRL - frozenset("\t")
30+
ILLEGAL_MULTILINE_BASIC_STR_CHARS: Final = ASCII_CTRL - frozenset("\t\n")
3131

32-
ILLEGAL_LITERAL_STR_CHARS = ILLEGAL_BASIC_STR_CHARS
33-
ILLEGAL_MULTILINE_LITERAL_STR_CHARS = ILLEGAL_MULTILINE_BASIC_STR_CHARS
32+
ILLEGAL_LITERAL_STR_CHARS: Final = ILLEGAL_BASIC_STR_CHARS
33+
ILLEGAL_MULTILINE_LITERAL_STR_CHARS: Final = ILLEGAL_MULTILINE_BASIC_STR_CHARS
3434

35-
ILLEGAL_COMMENT_CHARS = ILLEGAL_BASIC_STR_CHARS
35+
ILLEGAL_COMMENT_CHARS: Final = ILLEGAL_BASIC_STR_CHARS
3636

37-
TOML_WS = frozenset(" \t")
38-
TOML_WS_AND_NEWLINE = TOML_WS | frozenset("\n")
39-
BARE_KEY_CHARS = frozenset(
37+
TOML_WS: Final = frozenset(" \t")
38+
TOML_WS_AND_NEWLINE: Final = TOML_WS | frozenset("\n")
39+
BARE_KEY_CHARS: Final = frozenset(
4040
"abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "-_"
4141
)
42-
KEY_INITIAL_CHARS = BARE_KEY_CHARS | frozenset("\"'")
43-
HEXDIGIT_CHARS = frozenset("abcdef" "ABCDEF" "0123456789")
42+
KEY_INITIAL_CHARS: Final = BARE_KEY_CHARS | frozenset("\"'")
43+
HEXDIGIT_CHARS: Final = frozenset("abcdef" "ABCDEF" "0123456789")
4444

45-
BASIC_STR_ESCAPE_REPLACEMENTS = MappingProxyType(
45+
BASIC_STR_ESCAPE_REPLACEMENTS: Final = MappingProxyType(
4646
{
4747
"\\b": "\u0008", # backspace
4848
"\\t": "\u0009", # tab
49-
"\\n": "\u000A", # linefeed
50-
"\\f": "\u000C", # form feed
51-
"\\r": "\u000D", # carriage return
49+
"\\n": "\u000a", # linefeed
50+
"\\f": "\u000c", # form feed
51+
"\\r": "\u000d", # carriage return
5252
"\\e": "\u001b", # escape
5353
'\\"': "\u0022", # quote
54-
"\\\\": "\u005C", # backslash
54+
"\\\\": "\u005c", # backslash
5555
}
5656
)
5757

@@ -134,7 +134,7 @@ def load(fp: IO[bytes], /, *, parse_float: ParseFloat = float) -> dict[str, Any]
134134
return loads(s, parse_float=parse_float)
135135

136136

137-
def loads(s: str, /, *, parse_float: ParseFloat = float) -> dict[str, Any]: # noqa: C901
137+
def loads(s: str, /, *, parse_float: ParseFloat = float) -> dict[str, Any]:
138138
"""Parse TOML from a string."""
139139

140140
# The spec allows converting "\r\n" to "\n", even in string
@@ -209,10 +209,10 @@ class Flags:
209209
"""Flags that map to parsed keys/namespaces."""
210210

211211
# Marks an immutable namespace (inline array or inline table).
212-
FROZEN = 0
212+
FROZEN: Final = 0
213213
# Marks a nest that has been explicitly created and can no longer
214214
# be opened using the "[table]" syntax.
215-
EXPLICIT_NEST = 1
215+
EXPLICIT_NEST: Final = 1
216216

217217
def __init__(self) -> None:
218218
self._flags: dict[str, dict[Any, Any]] = {}
@@ -258,8 +258,8 @@ def is_(self, key: Key, flag: int) -> bool:
258258
cont = inner_cont["nested"]
259259
key_stem = key[-1]
260260
if key_stem in cont:
261-
cont = cont[key_stem]
262-
return flag in cont["flags"] or flag in cont["recursive_flags"]
261+
inner_cont = cont[key_stem]
262+
return flag in inner_cont["flags"] or flag in inner_cont["recursive_flags"]
263263
return False
264264

265265

@@ -665,7 +665,7 @@ def parse_basic_str(src: str, pos: Pos, *, multiline: bool) -> tuple[Pos, str]:
665665
pos += 1
666666

667667

668-
def parse_value( # noqa: C901
668+
def parse_value(
669669
src: str, pos: Pos, parse_float: ParseFloat
670670
) -> tuple[Pos, Any]:
671671
try:

Lib/tomllib/_re.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@
1010

1111
TYPE_CHECKING = False
1212
if TYPE_CHECKING:
13-
from typing import Any
13+
from typing import Any, Final
1414

1515
from ._types import ParseFloat
1616

17-
_TIME_RE_STR = r"""
17+
_TIME_RE_STR: Final = r"""
1818
([01][0-9]|2[0-3]) # hours
1919
:([0-5][0-9]) # minutes
2020
(?:
@@ -23,7 +23,7 @@
2323
)?
2424
"""
2525

26-
RE_NUMBER = re.compile(
26+
RE_NUMBER: Final = re.compile(
2727
r"""
2828
0
2929
(?:
@@ -42,8 +42,8 @@
4242
""",
4343
flags=re.VERBOSE,
4444
)
45-
RE_LOCALTIME = re.compile(_TIME_RE_STR, flags=re.VERBOSE)
46-
RE_DATETIME = re.compile(
45+
RE_LOCALTIME: Final = re.compile(_TIME_RE_STR, flags=re.VERBOSE)
46+
RE_DATETIME: Final = re.compile(
4747
rf"""
4848
([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) # date, e.g. 1988-10-27
4949
(?:

0 commit comments

Comments
 (0)