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
'[[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
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
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]]]:
# 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)
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")
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
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]
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),