Skip to content

Commit

Permalink
🍻 adjust global pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Sep 23, 2023
1 parent 1d04571 commit 681d01e
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 11 deletions.
10 changes: 7 additions & 3 deletions nepattern/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from .base import DATETIME as DATETIME
from .base import DICT as DICT
from .base import DirectPattern as DirectPattern
from .base import DirectTypePattern as DirectTypePattern
from .base import EMAIL as EMAIL
from .base import FLOAT as FLOAT
from .base import HEX as HEX
Expand Down Expand Up @@ -59,11 +60,14 @@
"ip": IP,
"url": URL,
"...": ANY,
"datetime": DATETIME,
"number": NUMBER,
list: LIST,
tuple: TUPLE,
set: SET,
dict: DICT,
}
)
global_patterns().set(PathFile)


global_patterns().sets([STRING, INTEGER, FLOAT, BOOLEAN, LIST, TUPLE, SET, DICT])
global_patterns()["number"] = NUMBER
global_patterns().sets([STRING, INTEGER, FLOAT, BOOLEAN, DATETIME])
14 changes: 14 additions & 0 deletions nepattern/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
class DirectPattern(BasePattern[TOrigin, TOrigin]):
"""直接判断"""

__slots__ = ("target",)

def __init__(self, target: TOrigin, alias: str | None = None):
self.target = target
super().__init__(mode=MatchMode.KEEP, origin=type(target), alias=alias or str(target))
Expand Down Expand Up @@ -88,6 +90,8 @@ def validate(self, input_: Any, default: Union[TDefault, Empty] = Empty) -> Vali
class DirectTypePattern(BasePattern[TOrigin, TOrigin]):
"""直接类型判断"""

__slots__ = ("target",)

def __init__(self, target: type[TOrigin], alias: str | None = None):
self.target = target
super().__init__(mode=MatchMode.KEEP, origin=target, alias=alias or target.__name__)
Expand All @@ -101,6 +105,12 @@ def match(self, input_: Any):
)
return input_

def prefixed(self):
return self

def suffixed(self):
return self

@overload
def validate(self, input_: TOrigin) -> ValidateResult[TOrigin, Literal[ResultFlag.VALID]]:
...
Expand Down Expand Up @@ -161,6 +171,8 @@ class UnionPattern(BasePattern[Any, _T]):
for_validate: list[BasePattern]
for_equal: list[str | object]

__slots__ = ("base", "optional", "for_validate", "for_equal")

def __init__(self, base: Iterable[_T | BasePattern[Any, _T]]):
self.base = list(base)
self.optional = False
Expand Down Expand Up @@ -344,6 +356,8 @@ def suffixed(self) -> Self:
class SwitchPattern(BasePattern[_TCase, _TSwtich]):
switch: dict[_TSwtich | ellipsis, _TCase]

__slots__ = ("switch",)

def __init__(self, data: dict[_TSwtich | ellipsis, _TCase]):
self.switch = data
super().__init__(mode=MatchMode.TYPE_CONVERT, origin=type(list(data.values())[0]))
Expand Down
4 changes: 2 additions & 2 deletions nepattern/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@

from tarina import Empty

from .base import UnionPattern
from .base import UnionPattern, NONE


@final
class Patterns(UserDict):
def __init__(self, name):
self.name = name
super().__init__({"": Empty})
super().__init__({"": NONE})

def set(self, target, alias=None, cover=True, no_alias=False):
"""
Expand Down
4 changes: 1 addition & 3 deletions nepattern/context.pyi
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from collections import UserDict
from typing import Any, Iterable, final

from tarina import Empty

from .core import BasePattern

@final
Expand All @@ -26,7 +24,7 @@ class Patterns(UserDict[Any, BasePattern]):

def create_local_patterns(
name: str,
data: dict[Any, BasePattern | type[Empty]] | None = None,
data: dict[Any, BasePattern] | None = None,
set_current: bool = True,
) -> Patterns:
"""
Expand Down
15 changes: 12 additions & 3 deletions test.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,9 +348,10 @@ def test_converters():
assert pattern_map["color"].validate("#ffffff").value() == "ffffff"
assert pattern_map["datetime"].validate("2011-11-04").value().day == 4
assert pattern_map["file"].validate("test.py").value()[:4] == b"from"
assert pattern_map[int].validate("123").value() == 123
assert pattern_map[float].validate("12.34").value() == 12.34
assert pattern_map[bool].validate("false").value() is False
assert pattern_map["number"].validate("123").value() == 123
assert pattern_map["int"].validate("123").value() == 123
assert pattern_map["float"].validate("12.34").value() == 12.34
assert pattern_map["bool"].validate("false").value() is False
assert pattern_map[list].validate("[1,2,3]").value() == [1, 2, 3]
assert pattern_map[tuple].validate("(1,2,3)").value() == (1, 2, 3)
assert pattern_map[set].validate("{1,2,3}").value() == {1, 2, 3}
Expand Down Expand Up @@ -536,6 +537,14 @@ def test_direct():
pat20_1.match("123")
except MatchFailed as e:
print(e)
pat21 = DirectTypePattern(int)
assert pat21.validate(123).value() == 123
assert pat21.validate("123").failed
assert pat21.validate(123, "123").value() == 123
assert pat21.prefixed().validate("1234").failed
assert pat21.suffixed().validate("4123").failed
assert pat21.match(123) == 123
assert pat21.match(456) == 456


def test_forward_red():
Expand Down

0 comments on commit 681d01e

Please sign in to comment.