Skip to content

Commit

Permalink
🐛 version 0.6.5
Browse files Browse the repository at this point in the history
fix depreciated warning in 3.11
  • Loading branch information
RF-Tar-Railt committed Feb 24, 2024
1 parent e3d8aa9 commit a95264a
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 41 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,8 @@ dmypy.json
# Cython debug symbols
cython_debug/

# PDM
.pdm-python

# PyCharm
.idea/
1 change: 1 addition & 0 deletions nepattern/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
from .base import TUPLE as TUPLE
from .base import URL as URL
from .base import UnionPattern as UnionPattern
from .base import WIDE_BOOLEAN as WIDE_BOOLEAN
from .context import Patterns as Patterns
from .context import all_patterns as all_patterns
from .context import create_local_patterns as create_local_patterns
Expand Down
84 changes: 62 additions & 22 deletions nepattern/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ def validate(self, input_: Any, default: Union[TDefault, Empty] = Empty) -> Vali
def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, DirectPattern) and self.target == other.target


class DirectTypePattern(BasePattern[TOrigin, TOrigin]):
"""直接类型判断"""

Expand Down Expand Up @@ -132,6 +133,7 @@ def validate(self, input_: Any, default: Union[TDefault, Empty] = Empty) -> Vali
def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, DirectTypePattern) and self.target == other.target


class RegexPattern(BasePattern[Match[str], str]):
"""针对正则的特化匹配,支持正则组"""

Expand Down Expand Up @@ -210,15 +212,19 @@ def __or__(self, other: BasePattern[Any, _T1]) -> UnionPattern[Union[_T, _T1]]:
def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, UnionPattern) and self.base == other.base


TSeq = TypeVar("TSeq", list, tuple, set)


class IterMode(str, Enum):
PRE = "pre"
SUF = "suf"
ALL = "all"


TIterMode = TypeVar("TIterMode", bound=IterMode)


class SequencePattern(BasePattern[TSeq, Union[str, TSeq]], Generic[TSeq, TIterMode]):
"""匹配列表或者元组或者集合"""

Expand Down Expand Up @@ -279,7 +285,6 @@ class MappingPattern(
value: BasePattern[TVal, Any]
itermode: TIterMode


def __init__(
self,
arg_key: BasePattern[TKey, Any],
Expand Down Expand Up @@ -443,6 +448,7 @@ def validate(self, input_: _T, default: Union[TDefault, Empty] = Empty) -> Valid
def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, AntiPattern) and self.base == other.base


TInput = TypeVar("TInput")


Expand All @@ -460,8 +466,10 @@ def __init__(
def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, CustomMatchPattern) and self.__func__ == other.__func__


NONE = CustomMatchPattern(type(None), lambda _, x: None, alias="none") # pragma: no cover


@final
class AnyPattern(BasePattern[Any, Any]):
def __init__(self):
Expand All @@ -471,7 +479,7 @@ def match(self, input_: Any) -> Any: # pragma: no cover
return input_

def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, AnyPattern)
return other.__class__ is AnyPattern


ANY = AnyPattern()
Expand All @@ -487,11 +495,13 @@ def match(self, input_: Any) -> str:
return str(input_)

def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, AnyStrPattern)
return other.__class__ is AnyStrPattern


AnyString = AnyStrPattern()
"""匹配任意内容并转为字符串的表达式"""


@final
class StrPattern(BasePattern[str, Any]):
def __init__(self):
Expand All @@ -500,20 +510,20 @@ def __init__(self):
def match(self, input_: Any) -> str:
if isinstance(input_, str):
return input_.value if isinstance(input_, Enum) else input_
elif isinstance(input_, (float, int, Decimal)):
return str(input_)
elif isinstance(input_, (bytes, bytearray)):
return input_.decode()
raise MatchFailed(
lang.require("nepattern", "type_error")
.format(type=input_.__class__, target=input_, expected="str, int, float, bytes, bytearray")
.format(type=input_.__class__, target=input_, expected="str | bytes | bytearray")
)

def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, StrPattern)

return other.__class__ is StrPattern


STRING = StrPattern()


@final
class BytesPattern(BasePattern[bytes, Any]):
def __init__(self):
Expand All @@ -524,19 +534,17 @@ def match(self, input_: Any) -> bytes:
return input_
elif isinstance(input_, str):
return input_.encode()
elif isinstance(input_, (float, int, Decimal)):
return str(input_).encode()
raise MatchFailed(
lang.require("nepattern", "type_error").format(
type=input_.__class__, target=input_, expected="bytes | str"
)
)

def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, BytesPattern)
return other.__class__ is BytesPattern

BYTES = BytesPattern()

BYTES = BytesPattern()


@final
Expand All @@ -557,7 +565,7 @@ def match(self, input_: Any) -> int:
) from e

def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, IntPattern)
return other.__class__ is IntPattern


INTEGER = IntPattern()
Expand All @@ -581,7 +589,8 @@ def match(self, input_: Any) -> float:
) from e

def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, FloatPattern)
return other.__class__ is FloatPattern


FLOAT = FloatPattern()
"""浮点数表达式"""
Expand All @@ -604,7 +613,8 @@ def match(self, input_: Any) -> float:
) from e

def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, NumberPattern)
return other.__class__ is NumberPattern


NUMBER = NumberPattern()
"""一般数表达式,既可以浮点数也可以整数 """
Expand All @@ -615,6 +625,34 @@ class BoolPattern(BasePattern[bool, Any]):
def __init__(self):
super().__init__(mode=MatchMode.TYPE_CONVERT, origin=bool, alias="bool")

def match(self, input_: Any) -> bool:
if input_ is True or input_ is False:
return input_
if isinstance(input_, bytes): # pragma: no cover
input_ = input_.decode()
if isinstance(input_, str):
input_ = input_.lower()
if input_ == "true":
return True
if input_ == "false":
return False
raise MatchFailed(
lang.require("nepattern", "content_error").format(target=input_, expected="bool")
)

def __calc_eq__(self, other): # pragma: no cover
return other.__class__ is BoolPattern


BOOLEAN = BoolPattern()
"""布尔表达式,只能接受true或false样式的量"""


@final
class WideBoolPattern(BasePattern[bool, Any]):
def __init__(self):
super().__init__(mode=MatchMode.TYPE_CONVERT, origin=bool, alias="bool")

BOOL_FALSE = {0, '0', 'off', 'f', 'false', 'n', 'no'}
BOOL_TRUE = {1, '1', 'on', 't', 'true', 'y', 'yes'}

Expand All @@ -640,11 +678,11 @@ def match(self, input_: Any) -> bool:
) from e

def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, BoolPattern)
return other.__class__ is BoolPattern


BOOLEAN = BoolPattern()
"""布尔表达式,只能接受true或false样式的量"""
WIDE_BOOLEAN = WideBoolPattern()
"""宽松布尔表达式,可以接受更多的布尔样式的量"""

LIST = BasePattern(r"(\[.+?\])", MatchMode.REGEX_CONVERT, list, alias="list")
TUPLE = BasePattern(r"(\(.+?\))", MatchMode.REGEX_CONVERT, tuple, alias="tuple")
Expand Down Expand Up @@ -689,7 +727,8 @@ def match(self, input_: str) -> int:
) from e

def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, HexPattern)
return other.__class__ is HexPattern


HEX = HexPattern()
"""匹配16进制数的表达式"""
Expand Down Expand Up @@ -717,7 +756,8 @@ def match(self, input_: Union[str, int, float]) -> datetime:
return DateParser.parse(input_)

def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, DateTimePattern)
return other.__class__ is DateTimePattern


DATETIME = DateTimePattern()
"""匹配时间的表达式"""
Expand All @@ -739,9 +779,9 @@ def match(self, input_: Any) -> Path:
lang.require("nepattern", "content_error").format(target=input_, expected="PathLike")
) from e


def __calc_eq__(self, other): # pragma: no cover
return isinstance(other, PathPattern)
return other.__class__ is PathPattern


PATH = PathPattern()

Expand Down
1 change: 1 addition & 0 deletions nepattern/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,4 +387,5 @@ def __or__(self, other):
f"unsupported operand type(s) for |: 'BasePattern' and '{other.__class__.__name__}'"
)


__all__ = ["MatchMode", "BasePattern", "ValidateResult", "TOrigin", "ResultFlag"]
12 changes: 8 additions & 4 deletions nepattern/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,30 @@

import dataclasses
from pathlib import Path
import sre_compile
import sys
from typing import TYPE_CHECKING, List, Pattern, Union

from tarina.lang import lang

if sys.version_info >= (3, 9): # pragma: no cover
from types import GenericAlias as CGenericAlias # noqa
else:
else: # pragma: no cover
CGenericAlias: type = type(List[int]) # noqa

if sys.version_info >= (3, 10): # pragma: no cover
from types import UnionType as CUnionType # noqa
else:
else: # pragma: no cover
CUnionType: type = type(Union[int, str]) # noqa

if sys.version_info >= (3, 11): # pragma: no cover
from re._compiler import compile as re_compile # noqa
else: # pragma: no cover
from sre_compile import compile as re_compile # noqa

if TYPE_CHECKING:
TPattern = Pattern[str]
else:
TPattern: type[Pattern[str]] = type(sre_compile.compile("", 0))
TPattern: type[Pattern[str]] = type(re_compile("", 0))
GenericAlias: type = type(List[int])
UnionType: type = type(Union[int, str])

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "nepattern"
version = "0.6.4"
version = "0.6.5"
description = "a complex pattern, support typing"
authors = [
{name = "RF-Tar-Railt", email = "rf_tar_railt@qq.com"},
Expand Down

0 comments on commit a95264a

Please sign in to comment.