]> ToastFreeware Gitweb - philipp/winterrodeln/wrpylib.git/blobdiff - wrpylib/wrvalidators.py
Remove unused imports.
[philipp/winterrodeln/wrpylib.git] / wrpylib / wrvalidators.py
index 48bc6b3cdabfe1fdab36e854153218ee8506987a..f48bb30f5db1d03bf9549f5b7a3bd1bebe140747 100644 (file)
@@ -12,7 +12,7 @@ import urllib.parse
 import re
 from collections import OrderedDict, namedtuple
 from email.errors import HeaderParseError
-from typing import Tuple, Optional, List, Any, Callable, Union, TypeVar, Dict
+from typing import Tuple, Optional, List, Callable, Union, TypeVar, Dict, NamedTuple
 
 import mwparserfromhell  # https://github.com/earwig/mwparserfromhell
 
@@ -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
 
 
@@ -438,11 +438,11 @@ def masked_email_from_str(value: str, mask='(at)', masked_only=False) -> Tuple[s
 def masked_email_to_str(value: Tuple[str, bool], mask='(at)') -> str:
     """Value is a tuple. The first entry is the email address, the second one is a boolean telling whether the
     email address should be masked."""
-    email, do_masking = value
-    email = email_to_str(email)
+    email_, do_masking = value
+    email_ = email_to_str(email_)
     if do_masking:
-        email = email.replace('@', mask)
-    return email
+        email_ = email_.replace('@', mask)
+    return email_
 
 
 def emails_from_str(value: str) -> Optional[List[Tuple[str, str]]]:
@@ -511,30 +511,30 @@ opt_phone_comment_opt_enum_converter = FromToConverter(lambda value: opt_phone_c
 # longitude/latitude converter
 # ----------------------------
 
-LonLat = namedtuple('LonLat', ['lon', 'lat'])
-
-
-lonlat_none = LonLat(None, None)
+class LonLat(NamedTuple):
+    lon: float
+    lat: float
 
 
 def lonlat_from_str(value: str) -> LonLat:
     """Converts a Winterrodeln geo string like '47.076207 N 11.453553 E' (being '<latitude> N <longitude> E'
     to the LonLat(lon, lat) named  tuple."""
     r = re.match(r'(\d+\.\d+) N (\d+\.\d+) E', value)
-    if r is None: raise ValueError("Coordinates '{}' have not a format like '47.076207 N 11.453553 E'".format(value))
+    if r is None:
+        raise ValueError(f"Coordinates '{value}' have not a format like '47.076207 N 11.453553 E'")
     return LonLat(float(r.groups()[1]), float(r.groups()[0]))
 
 
 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:
-    return opt_from_str(value, lonlat_from_str, lonlat_none)
+def opt_lonlat_from_str(value: str) -> Optional[LonLat]:
+    return opt_from_str(value, lonlat_from_str, None)
 
 
-def opt_lonlat_to_str(value: LonLat) -> str:
-    return opt_to_str(value, lonlat_to_str, lonlat_none)
+def opt_lonlat_to_str(value: Optional[LonLat]) -> str:
+    return opt_to_str(value, lonlat_to_str, None)
 
 
 opt_lonlat_converter = FromToConverter(opt_lonlat_from_str, opt_lonlat_to_str)
@@ -683,9 +683,9 @@ CACHET_REGEXP = [r'(Tiroler Naturrodelbahn-Gütesiegel) ([12]\d{3}) (leicht|mitt
 
 def single_cachet_german_from_str(value: str) -> Tuple[str, str, str]:
     for pattern in CACHET_REGEXP:
-        match = re.match(pattern, value)
-        if match:
-            return match.groups()
+        match_ = re.match(pattern, value)
+        if match_:
+            return match_.groups()
     raise ValueError(f"'{value}' is no valid cachet")
 
 
@@ -771,16 +771,17 @@ 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
     # check if keys are superfluous
     superfluous_keys = {str(p.name.strip()) for p in template.params} - set(converter_dict.keys())
     for key in superfluous_keys:
-        exceptions_dict[key] = ValueError('Superfluous parameter: "{}"'.format(key))
+        exceptions_dict[key] = ValueError(f'Superfluous parameter: "{key}"')
     if len(exceptions_dict) > 0:
-        raise ValueErrorList('{} error(s) occurred when parsing template parameters.'.format(len(exceptions_dict)), exceptions_dict)
+        raise ValueErrorList(f'{len(exceptions_dict)} error(s) occurred when parsing template parameters.',
+                             exceptions_dict)
     return result
 
 
@@ -795,9 +796,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]
 
 
@@ -870,7 +871,7 @@ GASTHAUSBOX_TEMPLATE_NAME = 'Gasthausbox'
 
 
 GASTHAUSBOX_DICT = OrderedDict([
-    ('Position', opt_lonlat_converter), # '47.583333 N 15.75 E'
+    ('Position', opt_lonlat_converter),  # '47.583333 N 15.75 E'
     ('Höhe', opt_uint_converter),
     ('Betreiber', opt_str_converter),
     ('Sitzplätze', opt_uint_converter),