8000 gh-104683: Modernise Tools/clinic/ (#104684) · python/cpython@19dd5aa · GitHub
[go: up one dir, main page]

Skip to content

Commit 19dd5aa

Browse files
gh-104683: Modernise Tools/clinic/ (#104684)
- Make some string interpolations more readable using f-strings or explicit parametrisation - Remove unneeded open() mode specifiers Co-authored-by: Erlend E. Aasland <erlend.aasland@protonmail.com>
1 parent 30488fa commit 19dd5aa

File tree

2 files changed

+31
-27
lines changed

2 files changed

+31
-27
lines changed

Tools/clinic/clinic.py

Lines changed: 30 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ def is_legal_py_identifier(s: str) -> bool:
208208
def ensure_legal_c_identifier(s: str) -> str:
209209
# for now, just complain if what we're given isn't legal
210210
if not is_legal_c_identifier(s):
211-
fail("Illegal C identifier: {}".format(s))
211+
fail("Illegal C identifier:", s)
212212
# but if we picked a C keyword, pick something else
213213
if s in c_keywords:
214214
return s + "_value"
@@ -991,7 +991,7 @@ def parser_body(prototype, *fields, declarations=''):
991991
argname_fmt = 'PyTuple_GET_ITEM(args, %d)'
992992

993993

994-
left_args = "{} - {}".format(nargs, max_pos)
994+
left_args = f"{nargs} - {max_pos}"
995995
max_args = NO_VARARG if (vararg != NO_VARARG) else max_pos
996996
parser_code = [normalize_snippet("""
997997
if (!_PyArg_CheckPositional("{name}", %s, %d, %s)) {{
@@ -1435,7 +1435,7 @@ def render_function(self, clinic, f):
14351435
first_optional = min(first_optional, i)
14361436

14371437
if p.is_vararg():
1438-
data.cleanup.append("Py_XDECREF({});".format(c.parser_name))
1438+
data.cleanup.append(f"Py_XDECREF({c.parser_name});")
14391439

14401440
# insert group variable
14411441
group = p.group
@@ -1487,8 +1487,7 @@ def render_function(self, clinic, f):
14871487

14881488
template_dict['c_basename'] = c_basename
14891489

1490-
methoddef_name = "{}_METHODDEF".format(c_basename.upper())
1491-
template_dict['methoddef_name'] = methoddef_name
1490+
template_dict['methoddef_name'] = c_basename.upper() + "_METHODDEF"
14921491

14931492
template_dict['docstring'] = self.docstring_for_c_string(f)
14941493

@@ -1791,7 +1790,7 @@ def is_stop_line(line):
17911790
for field in shlex.split(arguments):
17921791
name, equals, value = field.partition('=')
17931792
if not equals:
1794-
fail("Mangled Argument Clinic marker line: {!r}".format(line))
1793+
fail("Mangled Argument Clinic marker line:", repr(line))
17951794
d[name.strip()] = value.strip()
17961795

17971796
if self.verify:
@@ -1867,7 +1866,10 @@ def print_block(self, block, *, core_includes=False):
18671866
output += '\n'
18681867
write(output)
18691868

1870-
arguments="output={} input={}".format(compute_checksum(output, 16), compute_checksum(input, 16))
1869+
arguments = "output={output} input={input}".format(
1870+
output=compute_checksum(output, 16),
1871+
input=compute_checksum(input, 16)
1872+
)
18711873
write(self.language.checksum_line.format(dsl_name=dsl_name, arguments=arguments))
18721874
write("\n")
18731875

@@ -1976,7 +1978,7 @@ def dump(self):
19761978
def file_changed(filename: str, new_contents: str) -> bool:
19771979
"""Return true if file contents changed (meaning we must update it)"""
19781980
try:
1979-
with open(filename, 'r', encoding="utf-8") as fp:
1981+
with open(filename, encoding="utf-8") as fp:
19801982
old_contents = fp.read()
19811983
return old_contents != new_contents
19821984
except FileNotFoundError:
@@ -2132,7 +2134,7 @@ def parse(self, input):
21322134
dsl_name = block.dsl_name
21332135
if dsl_name:
21342136
if dsl_name not in self.parsers:
2135-
assert dsl_name in parsers, "No parser to handle {!r} block.".format(dsl_name)
2137+
assert dsl_name in parsers, f"No parser to handle {dsl_name!r} block."
21362138
self.parsers[dsl_name] = parsers[dsl_name](self)
21372139
parser = self.parsers[dsl_name]
21382140
try:
@@ -2172,7 +2174,7 @@ def parse(self, input):
21722174
"can't make directory {}!".format(
21732175
destination.filename, dirname))
21742176
if self.verify:
2175-
with open(destination.filename, "rt") as f:
2177+
with open(destination.filename) as f:
21762178
parser_2 = BlockParser(f.read(), language=self.language)
21772179
blocks = list(parser_2)
21782180
if (len(blocks) != 1) or (blocks[0].input != 'preserve\n'):
@@ -2239,7 +2241,7 @@ def parse_file(
22392241
except KeyError:
22402242
fail("Can't identify file type for file " + repr(filename))
22412243

2242-
with open(filename, 'r', encoding="utf-8") as f:
2244+
with open(filename, encoding="utf-8") as f:
22432245
raw = f.read()
22442246

22452247
# exit quickly if there are no clinic markers in the file
@@ -2537,9 +2539,9 @@ def get_displayname(self, i):
25372539
if i == 0:
25382540
return '"argument"'
25392541
if not self.is_positional_only():
2540-
return '''"argument '{}'"'''.format(self.name)
2542+
return f'"argument {self.name!r}"'
25412543
else:
2542-
return '"argument {}"'.format(i)
2544+
return f'"argument {i}"'
25432545

25442546

25452547
class LandMine:
@@ -2723,7 +2725,8 @@ def __init__(self,
27232725
if isinstance(self.default_type, type):
27242726
types_str = self.default_type.__name__
27252727
else:
2726-
types_str = ', '.join((cls.__name__ for cls in self.default_type))
2728+
names = [cls.__name__ for cls in self.default_type]
2729+
types_str = ', '.join(names)
27272730
fail("{}: default value {!r} for field {} is not of type {}".format(
27282731
self.__class__.__name__, default, name, types_str))
27292732
self.default = default
@@ -3955,7 +3958,7 @@ def set_template_dict(self, template_dict):
39553958
' Py_TYPE({0})->tp_new == base_tp->tp_new)'
39563959
).format(self.name)
39573960

3958-
line = '{} &&\n '.format(type_check)
3961+
line = f'{type_check} &&\n '
39593962
template_dict['self_type_check'] = line
39603963

39613964
type_object = self.function.cls.type_object
@@ -4011,10 +4014,12 @@ def declare(self, data):
40114014
data.return_value = data.converter_retval
40124015

40134016
def err_occurred_if(self, expr, data):
4014-
data.return_conversion.append('if (({}) && PyErr_Occurred()) {{\n goto exit;\n}}\n'.format(expr))
4017+
line = f'if (({expr}) && PyErr_Occurred()) {{\n goto exit;\n}}\n'
4018+
data.return_conversion.append(line)
40154019

40164020
def err_occurred_if_null_pointer(self, variable, data):
4017-
data.return_conversion.append('if ({} == NULL) {{\n goto exit;\n}}\n'.format(variable))
4021+
line = f'if ({variable} == NULL) {{\n goto exit;\n}}\n'
4022+
data.return_conversion.append(line)
40184023

40194024
def render(self, function, data):
40204025
"""
@@ -4477,13 +4482,13 @@ def state_modulename_name(self, line):
44774482
c_basename = c_basename.strip() or None
44784483

44794484
if not is_legal_py_identifier(full_name):
4480-
fail("Illegal function name: {}".format(full_name))
4485+
fail("Illegal function name:", full_name)
44814486
if c_basename and not is_legal_c_identifier(c_basename):
4482-
fail("Illegal C basename: {}".format(c_basename))
4487+
fail("Illegal C basename:", c_basename)
44834488

44844489
return_converter = None
44854490
if returns:
4486-
ast_input = "def x() -> {}: pass".format(returns)
4491+
ast_input = f"def x() -> {returns}: pass"
44874492
module = None
44884493
try:
44894494
module = ast.parse(ast_input)
@@ -4696,15 +4701,15 @@ def state_parameter(self, line):
46964701

46974702
module = None
46984703
try:
4699-
ast_input = "def x({}): pass".format(base)
4704+
ast_input = f"def x({base}): pass"
47004705
module = ast.parse(ast_input)
47014706
except SyntaxError:
47024707
try:
47034708
# the last = was probably inside a function call, like
47044709
# c: int(accept={str})
47054710
# so assume there was no actual default value.
47064711
default = None
4707-
ast_input = "def x({}): pass".format(line)
4712+
ast_input = f"def x({line}): pass"
47084713
module = ast.parse(ast_input)
47094714
except SyntaxError:
47104715
pass
@@ -4748,8 +4753,7 @@ def state_parameter(self, line):
47484753
self.parameter_state = self.ps_optional
47494754
default = default.strip()
47504755
bad = False
4751-
ast_input = "x = {}".format(default)
4752-
bad = False
4756+
ast_input = f"x = {default}"
47534757
try:
47544758
module = ast.parse(ast_input)
47554759

@@ -4856,7 +4860,7 @@ def bad_node(self, node):
48564860
dict = legacy_converters if legacy else converters
48574861
legacy_str = "legacy " if legacy else ""
48584862
if name not in dict:
4859-
fail('{} is not a valid {}converter'.format(name, legacy_str))
4863+
fail(f'{name} is not a valid {legacy_str}converter')
48604864
# if you use a c_name for the parameter, we just give that name to the converter
48614865
# but the parameter object gets the python name
48624866
converter = dict[name](c_name or parameter_name, parameter_name, self.function, value, **kwargs)
@@ -5388,7 +5392,7 @@ def main(argv):
53885392
for parameter_name, parameter in signature.parameters.items():
53895393
if parameter.kind == inspect.Parameter.KEYWORD_ONLY:
53905394
if parameter.default != inspect.Parameter.empty:
5391-
s = '{}={!r}'.format(parameter_name, parameter.default)
5395+
s = f'{parameter_name}={parameter.default!r}'
53925396
else:
53935397
s = parameter_name
53945398
parameters.append(s)

Tools/clinic/cpp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ def pop_stack() -> TokenAndCondition:
185185

186186
if __name__ == '__main__':
187187
for filename in sys.argv[1:]:
188-
with open(filename, "rt") as f:
188+
with open(filename) as f:
189189
cpp = Monitor(filename, verbose=True)
190190
print()
191191
print(filename)

0 commit comments

Comments
 (0)
0