Skip to content

Commit

Permalink
Add TypedString utility to reduce mixups with similarly-named string …
Browse files Browse the repository at this point in the history
…variables
  • Loading branch information
KevinMGranger committed Feb 14, 2022
1 parent ed0acc7 commit f25580c
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions exporters/pelorus/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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__()

0 comments on commit f25580c

Please sign in to comment.