PYTHON-3062 Make Regex generic (#860)
This commit is contained in:
parent
cbc7cc33e5
commit
c47557bc63
@ -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::
|
||||
|
||||
Loading…
Reference in New Issue
Block a user