Skip to content

Commit b399fea

Browse files
authored
Run pyupgrade to update Python syntax used (#2043)
* Automatic Changes Implemented by running pyupgrade --py38-plus on individual files: - Use fstrings where reasonable - replace use of really old % format specifier - removal of coding: utf-8 comment (it's the default encoding) - drop unnecessary Object argument from base class declarations - delete leading u from unicode-literals (python 3 strings support unicode characters) - delete unnecessary index arguments to {} for strings where we continue to use .format - pyupgrade is timid about f-string usage in order to maintain short and readable code - Use dict comprehension rather than whatever we were doing in nifake/unit_tests/test_grpc.py - delete unnecessary arguments from open() calls - Use set comprehension in metadata_add_all.py Discarded changes to test_converters.py. I believe we're not passing the right arguments for some tuple tests * tox -e codegen In addition to reflecting the changes in the previous commit, the copyright date in conf.py was updated to include 2024.
1 parent 7a5681e commit b399fea

File tree

117 files changed

+559
-581
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

117 files changed

+559
-581
lines changed

build/generate_template.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ def generate_template(template_name, template_params, dest_file, in_zip_file=Fal
1414
try:
1515
template_params['encoding_tag'] = '# -*- coding: utf-8 -*-'
1616
module_name = template_params['metadata'].config['module_name']
17-
lookup = TemplateLookup(directories=['src/{0}/templates'.format(module_name), 'build/templates'])
17+
lookup = TemplateLookup(directories=[f'src/{module_name}/templates', 'build/templates'])
1818
template = Template(filename=template_name, lookup=lookup)
1919
rendered_template = template.render(template_parameters=template_params)
2020

@@ -28,7 +28,7 @@ def generate_template(template_name, template_params, dest_file, in_zip_file=Fal
2828
lines = tback.source.split('\n')
2929

3030
# The underlying error.
31-
logging.error("\n%s: %s\n" % (str(tback.error.__class__.__name__), str(tback.error)))
31+
logging.error("\n{}: {}\n".format(str(tback.error.__class__.__name__), str(tback.error)))
3232
logging.error("Offending Template: %s\n" % template_name)
3333

3434
# Show a source listing of the template, with offending line marked.

build/helper/codegen_helper.py

Lines changed: 47 additions & 47 deletions
Large diffs are not rendered by default.

build/helper/documentation_helper.py

Lines changed: 40 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,9 @@ def get_rst_header_snippet(t, header_level='='):
5252

5353
def get_rst_picture_reference(tag, url, title, link, indent=0):
5454
'''Get rst formatted snippet that represents a picture'''
55-
ret_val = (' ' * indent) + '.. |{0}| image:: {1}\n'.format(tag, url)
56-
ret_val += (' ' * (indent + 4)) + ':alt: {0}\n'.format(title)
57-
ret_val += (' ' * (indent + 4)) + ':target: {0}\n'.format(link)
55+
ret_val = (' ' * indent) + f'.. |{tag}| image:: {url}\n'
56+
ret_val += (' ' * (indent + 4)) + f':alt: {title}\n'
57+
ret_val += (' ' * (indent + 4)) + f':target: {link}\n'
5858
return ret_val
5959

6060

@@ -101,7 +101,7 @@ def get_rst_admonition_snippet(node, admonition, d, config, indent=0):
101101
admonition_content = [admonition_content]
102102
a = ''
103103
for admonition_text in admonition_content:
104-
a += '\n\n' + (' ' * indent) + '.. {0}:: '.format(admonition)
104+
a += '\n\n' + (' ' * indent) + f'.. {admonition}:: '
105105
a += get_indented_docstring_snippet(_fix_references(node, admonition_text, config, make_link=True), indent + 4)
106106
return a
107107
else:
@@ -173,7 +173,7 @@ def get_docstring_admonition_snippet(node, admonition, d, config, indent=0, extr
173173
admonition_content = [admonition_content]
174174
a = ''
175175
for admonition_text in admonition_content:
176-
admonition_text = '{0}: {1}'.format(admonition.title(), admonition_text)
176+
admonition_text = f'{admonition.title()}: {admonition_text}'
177177
admonition_text = _fix_references(node, admonition_text, config, make_link=False)
178178
a += '\n' + extra_newline + (' ' * indent) + get_indented_docstring_snippet(admonition_text, indent)
179179
extra_newline = '\n'
@@ -270,15 +270,15 @@ def _replace_enum_python_name(e_match):
270270
ename = e_match.group(1)
271271
start_enum = config['start_enum']
272272
if e_match:
273-
ename = '{0}_VAL_{1}'.format(config['module_name'].upper(), ename.replace('\\', ''))
273+
ename = '{}_VAL_{}'.format(config['module_name'].upper(), ename.replace('\\', ''))
274274
enum, value = find_enum_by_value(config['enums'], ename, start_enum)
275275
if enum and enum['codegen_method'] != 'no':
276276
ename = enum['python_name'] + '.' + value['python_name']
277277

278278
if config['make_link']:
279-
return ':py:data:`~{0}.{1}`'.format(config['module_name'], ename)
279+
return ':py:data:`~{}.{}`'.format(config['module_name'], ename)
280280
else:
281-
return '{0}'.format(ename)
281+
return f'{ename}'
282282

283283

284284
def find_attribute_by_name(attributes, name):
@@ -287,7 +287,7 @@ def find_attribute_by_name(attributes, name):
287287
There should only be one so return that individual parameter and not a list
288288
'''
289289
attr = [attributes[x] for x in attributes if attributes[x]['name'] == name]
290-
assert len(attr) <= 1, '{0} attributes with name {1}. No more than one is allowed'.format(len(attr), name)
290+
assert len(attr) <= 1, f'{len(attr)} attributes with name {name}. No more than one is allowed'
291291
if len(attr) == 0:
292292
return None
293293
return attr[0]
@@ -311,11 +311,11 @@ def _replace_attribute_python_name(a_match):
311311

312312
if config['make_link']:
313313
if config['module_name'] == 'nitclk':
314-
return ':py:attr:`{0}.SessionReference.{1}`'.format(config['module_name'], aname)
314+
return ':py:attr:`{}.SessionReference.{}`'.format(config['module_name'], aname)
315315
else:
316-
return ':py:attr:`{0}.Session.{1}`'.format(config['module_name'], aname)
316+
return ':py:attr:`{}.Session.{}`'.format(config['module_name'], aname)
317317
else:
318-
return '{0}'.format(aname)
318+
return f'{aname}'
319319

320320

321321
def _replace_func_python_name(f_match):
@@ -336,18 +336,18 @@ def _replace_func_python_name(f_match):
336336
else:
337337
fname = config['functions'][fname]['python_name']
338338
except KeyError:
339-
print('Warning: "{0}" not found in function metadata. Typo? Generated code will be funky!'.format(fname))
339+
print(f'Warning: "{fname}" not found in function metadata. Typo? Generated code will be funky!')
340340
else:
341-
print('Unknown function name: {0}'.format(f_match.group(1)))
341+
print(f'Unknown function name: {f_match.group(1)}')
342342
print(config['functions'])
343343

344344
if config['make_link']:
345345
if config['module_name'] == 'nitclk':
346-
return ':py:func:`{0}.{1}`'.format(config['module_name'], fname)
346+
return ':py:func:`{}.{}`'.format(config['module_name'], fname)
347347
else:
348-
return ':py:meth:`{0}.Session.{1}`'.format(config['module_name'], fname)
348+
return ':py:meth:`{}.Session.{}`'.format(config['module_name'], fname)
349349
else:
350-
return '{0}'.format(fname)
350+
return f'{fname}'
351351

352352

353353
def _replace_urls(u_match):
@@ -393,10 +393,10 @@ def _fix_references(node, doc, cfg, make_link=False):
393393
if 'enum' in node:
394394
config['start_enum'] = node['enum']
395395

396-
attr_search_string = '{0}_ATTR_([A-Z0-9_]+)'.format(config['module_name'].upper())
397-
func_search_string = '{0}_([A-Za-z0-9_]+)'.format(config['c_function_prefix'].replace('_', ''))
398-
func_search_string_lower = '{0}_([A-Za-z0-9_]+)'.format(config['c_function_prefix'].lower().replace('_', ''))
399-
enum_search_string = '{0}_VAL_([A-Z0-9_]+)'.format(config['module_name'].upper())
396+
attr_search_string = '{}_ATTR_([A-Z0-9_]+)'.format(config['module_name'].upper())
397+
func_search_string = '{}_([A-Za-z0-9_]+)'.format(config['c_function_prefix'].replace('_', ''))
398+
func_search_string_lower = '{}_([A-Za-z0-9_]+)'.format(config['c_function_prefix'].lower().replace('_', ''))
399+
enum_search_string = '{}_VAL_([A-Z0-9_]+)'.format(config['module_name'].upper())
400400
attr_re = re.compile(attr_search_string)
401401
func_re = re.compile(func_search_string)
402402
func_lower_re = re.compile(func_search_string_lower)
@@ -409,7 +409,7 @@ def _fix_references(node, doc, cfg, make_link=False):
409409

410410
if 'driver_urls' in cfg:
411411
for url_key in cfg['driver_urls']:
412-
url_re = re.compile(r'{0}\((.+?)\)'.format(url_key))
412+
url_re = re.compile(fr'{url_key}\((.+?)\)')
413413
config['url_key'] = url_key
414414
doc = url_re.sub(_replace_urls, doc)
415415

@@ -439,7 +439,7 @@ def format_type_for_rst_documentation(param, numpy, config):
439439
if numpy and param['numpy']:
440440
p_type = param['numpy_type']
441441
elif param['enum'] is not None:
442-
p_type = ':py:data:`{0}.{1}`'.format(config['module_name'], param['enum'])
442+
p_type = ':py:data:`{}.{}`'.format(config['module_name'], param['enum'])
443443
else:
444444
p_type = param['type_in_documentation']
445445

@@ -448,11 +448,11 @@ def format_type_for_rst_documentation(param, numpy, config):
448448
if param['is_string'] is True and param['enum'] is None:
449449
p_type = 'str'
450450
elif param['is_buffer'] is True and numpy is True:
451-
p_type = 'numpy.array(dtype=numpy.{0})'.format(get_numpy_type_for_api_type(param['type'], config))
451+
p_type = 'numpy.array(dtype=numpy.{})'.format(get_numpy_type_for_api_type(param['type'], config))
452452
elif param['use_list'] is True:
453453
p_type = 'list of ' + p_type
454454
elif param['use_array'] is True:
455-
p_type = 'array.array("{0}")'.format(get_array_type_for_api_type(param['type']))
455+
p_type = 'array.array("{}")'.format(get_array_type_for_api_type(param['type']))
456456

457457
return p_type
458458

@@ -482,7 +482,7 @@ def get_function_rst(function, method_template, numpy, config, indent=0, method_
482482
if function['has_repeated_capability'] is True:
483483
function['documentation']['tip'] = rep_cap_method_desc.format(config['module_name'], function['repeated_capability_type'], function['python_name'])
484484

485-
rst = '.. py:{0}:: {1}{2}('.format(method_or_function, function['python_name'], suffix)
485+
rst = '.. py:{}:: {}{}('.format(method_or_function, function['python_name'], suffix)
486486
rst += get_params_snippet(function, session_method) + ')'
487487
indent += 4
488488
rst += get_documentation_for_node_rst(function, config, indent)
@@ -491,19 +491,19 @@ def get_function_rst(function, method_template, numpy, config, indent=0, method_
491491
if len(input_params) > 0:
492492
rst += '\n'
493493
for p in input_params:
494-
rst += '\n' + (' ' * indent) + ':param {0}:'.format(p['python_name']) + '\n'
494+
rst += '\n' + (' ' * indent) + ':param {}:'.format(p['python_name']) + '\n'
495495
rst += get_documentation_for_node_rst(p, config, indent + 4)
496496

497497
p_type = format_type_for_rst_documentation(p, numpy, config)
498-
rst += '\n' + (' ' * indent) + ':type {0}: '.format(p['python_name']) + p_type
498+
rst += '\n' + (' ' * indent) + ':type {}: '.format(p['python_name']) + p_type
499499

500500
output_params = filter_parameters(function['parameters'], output_parameters)
501501
if len(output_params) > 1:
502502
rst += '\n\n' + (' ' * indent) + ':rtype: tuple (' + ', '.join([p['python_name'] for p in output_params]) + ')\n\n'
503503
rst += (' ' * (indent + 4)) + 'WHERE\n'
504504
for p in output_params:
505505
p_type = format_type_for_rst_documentation(p, numpy, config)
506-
rst += '\n' + (' ' * (indent + 4)) + '{0} ({1}): '.format(p['python_name'], p_type) + '\n'
506+
rst += '\n' + (' ' * (indent + 4)) + '{} ({}): '.format(p['python_name'], p_type) + '\n'
507507
rst += get_documentation_for_node_rst(p, config, indent + 8)
508508
elif len(output_params) == 1:
509509
p = output_params[0]
@@ -527,11 +527,11 @@ def _format_type_for_docstring(param, numpy, config):
527527
if param['is_string'] is True and param['enum'] is None:
528528
p_type = 'str'
529529
elif param['is_buffer'] is True and numpy is True:
530-
p_type = 'numpy.array(dtype=numpy.{0})'.format(get_numpy_type_for_api_type(param['type'], config))
530+
p_type = 'numpy.array(dtype=numpy.{})'.format(get_numpy_type_for_api_type(param['type'], config))
531531
elif param['use_list'] is True:
532532
p_type = 'list of ' + p_type
533533
elif param['use_array'] is True:
534-
p_type = 'array.array("{0}")'.format(get_array_type_for_api_type(param['type']))
534+
p_type = 'array.array("{}")'.format(get_array_type_for_api_type(param['type']))
535535

536536
return p_type
537537

@@ -564,7 +564,7 @@ def get_function_docstring(function, numpy, config, indent=0):
564564
if len(input_params) > 0:
565565
docstring += '\n\n' + (' ' * indent) + 'Args:'
566566
for p in input_params:
567-
docstring += '\n' + (' ' * (indent + 4)) + '{0} ({1}):'.format(p['python_name'], _format_type_for_docstring(p, numpy, config))
567+
docstring += '\n' + (' ' * (indent + 4)) + '{} ({}):'.format(p['python_name'], _format_type_for_docstring(p, numpy, config))
568568
ds = get_documentation_for_node_docstring(p, config, indent + 8)
569569
if len(ds) > 0:
570570
docstring += ' ' + ds
@@ -574,7 +574,7 @@ def get_function_docstring(function, numpy, config, indent=0):
574574
if len(output_params) > 0:
575575
docstring += '\n\n' + (' ' * indent) + 'Returns:'
576576
for p in output_params:
577-
docstring += '\n' + (' ' * (indent + 4)) + '{0} ({1}):'.format(p['python_name'], _format_type_for_docstring(p, numpy, config))
577+
docstring += '\n' + (' ' * (indent + 4)) + '{} ({}):'.format(p['python_name'], _format_type_for_docstring(p, numpy, config))
578578
ds = get_documentation_for_node_docstring(p, config, indent + 8)
579579
if len(ds) > 0:
580580
docstring += ' ' + ds
@@ -621,21 +621,21 @@ def as_rest_table(data, header=True):
621621
line_marker = '-'
622622

623623
meta_template = vertical_separator.join(['{{{{{0}:{{{0}}}}}}}'.format(i) for i in range(num_elts)])
624-
template = '{0}{1}{2}'.format(start_of_line, meta_template.format(*sizes), end_of_line)
624+
template = f'{start_of_line}{meta_template.format(*sizes)}{end_of_line}'
625625
# determine top/bottom borders
626626
to_separator = {ord('|'): '+', ord(' '): '-'}
627627

628628
start_of_line = start_of_line.translate(to_separator)
629629
vertical_separator = vertical_separator.translate(to_separator)
630630
end_of_line = end_of_line.translate(to_separator)
631-
separator = '{0}{1}{2}'.format(start_of_line, vertical_separator.join([x * line_marker for x in sizes]), end_of_line)
631+
separator = f'{start_of_line}{vertical_separator.join([x * line_marker for x in sizes])}{end_of_line}'
632632
# determine header separator
633633
th_separator_tr = {ord('-'): '='}
634634
start_of_line = start_of_line.translate(th_separator_tr)
635635
line_marker = line_marker.translate(th_separator_tr)
636636
vertical_separator = vertical_separator.translate(th_separator_tr)
637637
end_of_line = end_of_line.translate(th_separator_tr)
638-
th_separator = '{0}{1}{2}'.format(start_of_line, vertical_separator.join([x * line_marker for x in sizes]), end_of_line)
638+
th_separator = f'{start_of_line}{vertical_separator.join([x * line_marker for x in sizes])}{end_of_line}'
639639
# prepare result
640640
table.append(separator)
641641
# set table header
@@ -719,7 +719,7 @@ def square_up_tables(config):
719719

720720
def _need_func_note(nd, config):
721721
'''Determine if we need the extra note about function names not matching anything in Python'''
722-
func_re = re.compile('{0}_([A-Za-z0-9_]+)'.format(config['c_function_prefix'].replace('_', '')))
722+
func_re = re.compile('{}_([A-Za-z0-9_]+)'.format(config['c_function_prefix'].replace('_', '')))
723723
for m in func_re.finditer(nd):
724724
fname = m.group(1).replace('.', '').replace(',', '').replace('\\', '')
725725
try:
@@ -732,7 +732,7 @@ def _need_func_note(nd, config):
732732

733733
def _need_attr_note(nd, config):
734734
'''Determine if we need the extra note about attribute names not matching anything in Python'''
735-
attr_re = re.compile('{0}_ATTR_([A-Z0-9_]+)'.format(config['module_name'].upper()))
735+
attr_re = re.compile('{}_ATTR_([A-Z0-9_]+)'.format(config['module_name'].upper()))
736736
for m in attr_re.finditer(nd):
737737
aname = m.group(1).replace('\\', '')
738738
attr = find_attribute_by_name(config['attributes'], aname)
@@ -744,9 +744,9 @@ def _need_attr_note(nd, config):
744744

745745
def _need_enum_note(nd, config, start_enum=None):
746746
'''Determine if we need the extra note about enum names not matching anything in Python'''
747-
enum_re = re.compile('{0}_VAL_([A-Z0-9_]+)'.format(config['module_name'].upper()))
747+
enum_re = re.compile('{}_VAL_([A-Z0-9_]+)'.format(config['module_name'].upper()))
748748
for m in enum_re.finditer(nd):
749-
ename = '{0}_VAL_{1}'.format(config['module_name'].upper(), m.group(1).replace('\\', ''))
749+
ename = '{}_VAL_{}'.format(config['module_name'].upper(), m.group(1).replace('\\', ''))
750750
enum, _ = find_enum_by_value(config['enums'], ename, start_enum=start_enum)
751751
if not enum or enum['codegen_method'] == 'no':
752752
return True

build/helper/documentation_snippets.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def close_function_def_for_doc(functions, config):
106106
function_def['documentation']['note'].append(close_function_note)
107107
function_def['python_name'] = 'close'
108108
else:
109-
assert False, "No '{}' function defined".format(close_name)
109+
assert False, f"No '{close_name}' function defined"
110110

111111
return function_def
112112

@@ -138,7 +138,7 @@ def initiate_function_def_for_doc(functions, config):
138138
function_def['documentation']['note'].append(initiate_function_note)
139139
function_def['python_name'] = 'initiate'
140140
else:
141-
assert False, "No '{}' function defined".format(session_context_manager_initiate)
141+
assert False, f"No '{session_context_manager_initiate}' function defined"
142142

143143
return function_def
144144

build/helper/helper.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def get_numpy_type_for_api_type(api_type, config):
8686
if c['ctypes_type'] == api_type:
8787
return c['python_name']
8888
# We didn't find it so assert
89-
assert False, 'Unknown value for api_type: {0}'.format(api_type)
89+
assert False, f'Unknown value for api_type: {api_type}'
9090

9191

9292
def get_array_type_for_api_type(api_type):
@@ -98,7 +98,7 @@ def get_array_type_for_api_type(api_type):
9898
if api_type in _type_map and _type_map[api_type]['array_type'] is not None:
9999
return _type_map[api_type]['array_type']
100100
else:
101-
raise TypeError('Only simple types allowed for arrays: {0}'.format(api_type))
101+
raise TypeError(f'Only simple types allowed for arrays: {api_type}')
102102

103103

104104
def get_development_status(config):

0 commit comments

Comments
 (0)