]> ToastFreeware Gitweb - philipp/winterrodeln/wrpylib.git/commitdiff
Make use of format strings.
authorPhilipp Spitzer <philipp@spitzer.priv.at>
Fri, 6 Aug 2021 20:31:57 +0000 (22:31 +0200)
committerPhilipp Spitzer <philipp@spitzer.priv.at>
Fri, 6 Aug 2021 20:31:57 +0000 (22:31 +0200)
wrpylib/mwmarkup.py
wrpylib/wrmwcache.py
wrpylib/wrmwmarkup.py
wrpylib/wrvalidators.py

index 7adcce45d5dc95e13642ad49d6095692f17ad376..a5d83ba5714c36f90f961dfb3198e4a76eec86e5 100644 (file)
@@ -28,13 +28,13 @@ def format_template_table(template: Template, keylen: Optional[int] = None):
     if keylen is None:
         shown_keys = [len(param.name.strip()) for param in template.params if param.showkey]
         keylen = max(shown_keys) if shown_keys else 0
-    template.name = '{}\n'.format(template.name.strip())
+    template.name = f'{template.name.strip()}\n'
     for param in template.params:
         if param.showkey:
             param.name = ' {{:{}}} '.format(keylen).format(param.name.strip())
         value = param.value.strip()
         if len(value) > 0:
-            param.value = ' {}\n'.format(value)
+            param.value = f' {value}\n'
         else:
             param.value = '\n'
 
index 5cb4c1e526049d0b707d3d3b9ffbe9a2ca2980f5..deceff8922b2cce00300479c605eca2702b0e19b 100644 (file)
@@ -61,7 +61,7 @@ def update_wrsledruncache(connection):
             connection.execute(wrsledruncache.insert(sledrun.__dict__))
         except ValueError as e:
             transaction.rollback()
-            error_msg = "Error at sled run '{0}': {1}".format(sledrun_page.page_title, str(e))
+            error_msg = f"Error at sled run '{sledrun_page.page_title}': {e}"
             raise UpdateCacheError(error_msg, sledrun_page.page_title, e)
     transaction.commit()
 
@@ -149,7 +149,7 @@ def update_wrreportcache(connection, page_id=None):
           'if(author_userid is null, null, author_username) as author_username from wrreport ' \
           'where {0}`condition` is not null and date_invalid > now() and delete_date is null ' \
           'order by page_id, date_report desc, date_entry desc' \
-          .format('' if page_id is None else 'page_id={0} and '.format(page_id))
+          .format('' if page_id is None else f'page_id={page_id} and ')
     cursor = connection.execute(sql)
     page_id = None
     row_list = []
@@ -243,17 +243,17 @@ def update_wrmapcache(connection):
                         'anfahrt': 'recommendedcarroute',
                         'linie': 'line'}
                     path_type = path_types[properties['type']]
-                    path = ", ".join(["{0} {1}".format(lon, lat) for lon, lat in coordinates])
-                    path = 'LineString({0})'.format(path)
+                    path = ", ".join([f"{lon} {lat}" for lon, lat in coordinates])
+                    path = f'LineString({path})'
                     if path_type == 'recommendedcarroute':
                         continue
                     sql = 'insert into wrmappathcache (path, page_id, type) values (GeomFromText(%s), %s, %s)'
                     connection.execute(sql, (path, sledrun_page.page_id, path_type))
 
                 else:
-                    raise RuntimeError('Unknown feature type {0}'.format(properties['type']))
+                    raise RuntimeError(f'Unknown feature type {properties["type"]}')
         except RuntimeError as e:
-            error_msg = "Error at sledrun '{0}': {1}".format(sledrun_page.page_title, str(e))
+            error_msg = f"Error at sledrun '{sledrun_page.page_title}': {e}"
             transaction.rollback()
             raise UpdateCacheError(error_msg, sledrun_page.page_title, e)
     transaction.commit()
index 4294393b237cdd0e528ce72f99b829f54dd26d01..f2ea5c871ec7cee1f21a05fd42d98ba59c68004d 100644 (file)
@@ -169,7 +169,7 @@ def parse_wrmap_coordinates(coords: str) -> List[List[float]]:
     else:
         if pos == len(coords):
             return result
-    raise RuntimeError('Wrong coordinate format: {}'.format(coords))
+    raise RuntimeError(f'Wrong coordinate format: {coords}')
 
 
 WRMAP_POINT_TYPES = ['gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'foto', 'verleih', 'punkt']
@@ -204,7 +204,7 @@ def parse_wrmap(wikitext):
         wrmap_xml = xml.etree.ElementTree.fromstring(wikitext)
     except xml.etree.ElementTree.ParseError as e:
         row, column = e.position
-        raise ParseError("XML parse error on row {}, column {}: {}".format(row, column, e))
+        raise ParseError(f"XML parse error on row {row}, column {column}: {e}")
     if wrmap_xml.tag not in ['wrmap', 'wrgmap']:
         raise ParseError('No valid tag name')
 
@@ -215,7 +215,7 @@ def parse_wrmap(wikitext):
         is_point = feature.tag in WRMAP_POINT_TYPES
         is_line = feature.tag in WRMAP_LINE_TYPES
         if not is_point and not is_line:
-            raise ParseError('Unknown element <{}>.'.format(feature.tag))
+            raise ParseError(f'Unknown element <{feature.tag}>.')
 
         # point
         if is_point:
@@ -261,14 +261,14 @@ def parse_wrmap(wikitext):
             try:
                 properties[k] = float(v)
             except ValueError:
-                raise ParseError('Attribute "{}" has to be a float value.'.format(k))
+                raise ParseError(f'Attribute "{k}" has to be a float value.')
         elif k in ['zoom', 'width', 'height']:
             try:
                 properties[k] = int(v)
             except ValueError:
-                raise ParseError('Attribute "{}" has to be an integer value.'.format(k))
+                raise ParseError(f'Attribute "{k}" has to be an integer value.')
         else:
-            raise ParseError('Unknown attribute "{}".'.format(k))
+            raise ParseError(f'Unknown attribute "{k}".')
 
     geojson = {
         'type': 'FeatureCollection',
@@ -281,7 +281,7 @@ def parse_wrmap(wikitext):
 def create_wrmap_coordinates(coords):
     result = []
     for coord in coords:
-        result.append('{:.6f} N {:.6f} E'.format(coord[1], coord[0]))
+        result.append(f'{coord[1]:.6f} N {coord[0]:.6f} E')
     return '\n'.join(result)
  
 
@@ -291,7 +291,7 @@ def create_wrmap(geojson):
     wrmap_xml.text = '\n\n'
     for k, v in geojson['properties'].items():
         if k in ['lon', 'lat']:
-            wrmap_xml.attrib[k] = '{:.6f}'.format(v)
+            wrmap_xml.attrib[k] = f'{v:.6f}'
         else:
             wrmap_xml.attrib[k] = str(v)
 
index 7f22cf0dc4205be739ab33c7bff26044fc69fbed..cdac2a509df0244f3aafa6d778306d292018e3d3 100644 (file)
@@ -384,7 +384,7 @@ def wikipage_from_str(value: str) -> str:
     '[[Birgitzer Alm]]' => '[[Birgitzer Alm]]'
     """
     if re.match(r'\[\[[^\[\]]+]]$', value) is None:
-        raise ValueError('No valid wiki page name "{}"'.format(value))
+        raise ValueError(f'No valid wiki page name "{value}"')
     return value
 
 
@@ -417,7 +417,7 @@ def email_from_str(value: str) -> str:
     try:
         email.headerregistry.Address(addr_spec=value)
     except HeaderParseError as e:
-        raise ValueError('Invalid email address: {}'.format(value), e)
+        raise ValueError(f'Invalid email address: {value}', e)
     return value
 
 
@@ -527,7 +527,7 @@ def lonlat_from_str(value: str) -> LonLat:
 
 
 def lonlat_to_str(value: LonLat) -> str:
-    return '{:.6f} N {:.6f} E'.format(value.lat, value.lon)
+    return f'{value.lat:.6f} N {value.lon:.6f} E'
 
 
 def opt_lonlat_from_str(value: str) -> LonLat:
@@ -772,7 +772,7 @@ def wikibox_from_template(template, converter_dict):
     for key, converter in converter_dict.items():
         try:
             if not template.has(key):
-                raise ValueError('Missing parameter "{}"'.format(key))
+                raise ValueError(f'Missing parameter "{key}"')
             result[key] = converter.from_str(str(template.get(key).value.strip()))
         except ValueError as e:
             exceptions_dict[key] = e
@@ -797,9 +797,9 @@ def template_from_str(value, name):
     wikicode = mwparserfromhell.parse(value)
     template_list = wikicode.filter_templates(recursive=False, matches=lambda t: t.name.strip() == name)
     if len(template_list) == 0:
-        raise ValueError('No "{}" template was found'.format(name))
+        raise ValueError(f'No "{name}" template was found')
     if len(template_list) > 1:
-        raise ValueError('{} "{}" templates were found'.format(len(template_list), name))
+        raise ValueError(f'{len(template_list)} "{name}" templates were found')
     return template_list[0]