From c47557bc63cd60d5f709da3ec6fbdaa9fb783c7e Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 10 Feb 2022 18:59:26 -0600 Subject: [PATCH] PYTHON-3062 Make Regex generic (#860) --- bson/regex.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/bson/regex.py b/bson/regex.py index 317c65049..3e9847719 100644 --- a/bson/regex.py +++ b/bson/regex.py @@ -16,7 +16,7 @@ """ import re -from typing import Any, Pattern, Type, Union +from typing import Any, Generic, Pattern, Type, TypeVar, Union from bson._helpers import _getstate_slots, _setstate_slots from bson.son import RE_TYPE @@ -40,7 +40,10 @@ def str_flags_to_int(str_flags: str) -> int: return flags -class Regex(object): +_T = TypeVar("_T", str, bytes) + + +class Regex(Generic[_T]): """BSON regular expression data.""" __slots__ = ("pattern", "flags") @@ -51,7 +54,7 @@ class Regex(object): _type_marker = 11 @classmethod - def from_native(cls: Type["Regex"], regex: Pattern[Any]) -> "Regex": + def from_native(cls: Type["Regex"], regex: "Pattern[_T]") -> "Regex[_T]": """Convert a Python regular expression into a ``Regex`` instance. Note that in Python 3, a regular expression compiled from a @@ -80,7 +83,7 @@ class Regex(object): return Regex(regex.pattern, regex.flags) - def __init__(self, pattern: Union[str, bytes], flags: Union[str, int] = 0) -> None: + def __init__(self, pattern: _T, flags: Union[str, int] = 0) -> None: """BSON regular expression data. This class is useful to store and retrieve regular expressions that are @@ -93,7 +96,7 @@ class Regex(object): """ if not isinstance(pattern, (str, bytes)): raise TypeError("pattern must be a string, not %s" % type(pattern)) - self.pattern = pattern + self.pattern: _T = pattern if isinstance(flags, str): self.flags = str_flags_to_int(flags) @@ -116,7 +119,7 @@ class Regex(object): def __repr__(self): return "Regex(%r, %r)" % (self.pattern, self.flags) - def try_compile(self) -> Pattern[Any]: + def try_compile(self) -> "Pattern[_T]": """Compile this :class:`Regex` as a Python regular expression. .. warning::