Make f-strings backward compatible for Python < 3.12

This commit is contained in:
2026-03-12 22:10:51 +01:00
parent b00e5d9829
commit 264f8a0083
3 changed files with 14 additions and 10 deletions
+10 -9
View File
@@ -328,7 +328,7 @@ class JSONObject(JSONType):
current_key = ''
current_value = None
else:
raise JSONObjectSyntaxError(f'expected \':\'')
raise JSONObjectSyntaxError('expected \':\'')
if current_key:
if current_value is not None:
@@ -336,7 +336,7 @@ class JSONObject(JSONType):
current_key = ''
current_value = None
else:
raise JSONObjectSyntaxError(f'expected value')
raise JSONObjectSyntaxError('expected value')
json_object = {}
for k, v in _object.items():
@@ -471,27 +471,27 @@ def parse_type(value: str) -> typing.Type[JSONType]:
if current_value is None:
current_value = ''
else:
raise JSONObjectSyntaxError(f'expected \',\'')
raise JSONObjectSyntaxError('expected \',\'')
if not string and c == ',' and not arrays and not objects:
if current_value is not None:
if parse_type(current_key) != JSONString:
raise JSONObjectSyntaxError(f'keys have to be strings')
raise JSONObjectSyntaxError('keys have to be strings')
parse_type(current_value[:-1])
current_key = ''
current_value = None
else:
raise JSONObjectSyntaxError(f'expected \':\'')
raise JSONObjectSyntaxError('expected \':\'')
if current_key:
if current_value is not None:
if parse_type(current_key) != JSONString:
raise JSONObjectSyntaxError(f'keys have to be strings')
raise JSONObjectSyntaxError('keys have to be strings')
parse_type(current_value)
current_key = ''
current_value = None
else:
raise JSONObjectSyntaxError(f'expected value')
raise JSONObjectSyntaxError('expected value')
if string:
raise JSONStringSyntaxError('unterminated string literal')
@@ -568,11 +568,12 @@ def parse_type(value: str) -> typing.Type[JSONType]:
if value[0] != '"':
raise JSONStringSyntaxError(f'expected \'"\' as first char, got \'{value[0]}\'')
if '\n' in value:
raise JSONStringSyntaxError(f'line feeds are not allowed inside of strings. Use escape sequences.')
raise JSONStringSyntaxError('line feeds are not allowed inside of strings. Use escape sequences.')
if value.count('"') < 2:
raise JSONStringSyntaxError('unterminated string literal')
if value.count('"') - value.count('\\"') > 2 or value[-1] != '"':
raise JSONStringSyntaxError(f'unexpected token: \'{"\"".join(value.split("\"")[2:])}\'')
# backward compatibility (in Python < 3.12, f-string expression parts could not contain backslashes)
raise JSONStringSyntaxError('unexpected token: \'' + '\"'.join(value.split('\"')[2:]) + '\'')
parse_escape_sequences(value)
return JSONString