From 11b0863a652033e8ca70bd8f5352219d41372034 Mon Sep 17 00:00:00 2001 From: Kelly Brazil Date: Sat, 15 Oct 2022 13:44:44 -0700 Subject: [PATCH] Use TypedDict for more granular typing --- jc/utils.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/jc/utils.py b/jc/utils.py index 34b70e9c..dfef6bec 100644 --- a/jc/utils.py +++ b/jc/utils.py @@ -6,7 +6,16 @@ import shutil from datetime import datetime, timezone from textwrap import TextWrapper from functools import lru_cache -from typing import List, Dict, Iterable, Union, Optional, TextIO +from typing import List, Dict, Iterable, Union, Optional, TypedDict, TextIO + +TSFormatType = TypedDict( + 'TSFormatType', + { + 'id': int, + 'format': str, + 'locale': Optional[str] + } +) def _asciify(string: str) -> str: @@ -381,7 +390,7 @@ class timestamp: If the conversion completely fails, all fields will be None. """ - formats: tuple[Dict[str, Union[int, str, None]], ...] = ( + formats: tuple[TSFormatType, ...] = ( {'id': 1000, 'format': '%a %b %d %H:%M:%S %Y', 'locale': None}, # manual C locale format conversion: Tue Mar 23 16:12:11 2021 or Tue Mar 23 16:12:11 IST 2021 {'id': 1100, 'format': '%a %b %d %H:%M:%S %Y %z', 'locale': None}, # git date output: Thu Mar 5 09:17:40 2020 -0800 {'id': 1300, 'format': '%Y-%m-%dT%H:%M:%S.%f%Z', 'locale': None}, # ISO Format with UTC (found in syslog 5424): 2003-10-11T22:14:15.003Z @@ -517,10 +526,10 @@ class timestamp: for fmt in optimized_formats: try: - locale.setlocale(locale.LC_TIME, fmt['locale']) # type: ignore - dt = datetime.strptime(normalized_datetime, fmt['format']) # type: ignore + locale.setlocale(locale.LC_TIME, fmt['locale']) + dt = datetime.strptime(normalized_datetime, fmt['format']) timestamp_naive = int(dt.replace(tzinfo=None).timestamp()) - timestamp_obj['format'] = fmt['id'] # type: ignore + timestamp_obj['format'] = fmt['id'] locale.setlocale(locale.LC_TIME, None) break except Exception: