From f25580cad83a4586d9ac8a7c6aa657bea6349b0c Mon Sep 17 00:00:00 2001 From: Kevin M Granger Date: Mon, 14 Feb 2022 16:44:45 -0500 Subject: [PATCH] Add TypedString utility to reduce mixups with similarly-named string variables --- exporters/pelorus/utils.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/exporters/pelorus/utils.py b/exporters/pelorus/utils.py index 96d1c7e04..2f397d53b 100644 --- a/exporters/pelorus/utils.py +++ b/exporters/pelorus/utils.py @@ -4,6 +4,7 @@ in kubernetes that are not so idiomatic to deal with. """ import dataclasses +from collections import UserString from collections.abc import Iterable from typing import Any, Optional, Protocol, TypeVar, Union, overload @@ -150,3 +151,31 @@ def message(self): f"{'.'.join(self.path[self.path_slice])} was {self.value}, " "so we could not continue." ) + + +class TypedString(UserString): + """ + A "wrapped" string that can only test for equality between TypedStrings + of the same type, or a regular string. + + This helps when strings representing different things are easily confused-- + such as PipelineRun names versus Pipeline names. + """ + + def __eq__(self, other): + if isinstance(other, TypedString): + if type(self) is type(other): + return self.data == other.data + else: + return False + elif type(other) is str: + return self.data == other + else: + return NotImplemented + + def __repr__(self): + type_name = type(self).__name__ + return f'{type_name}("{super().__str__()}")' + + def __hash__(self) -> int: + return super().__hash__()