-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathabc.py
69 lines (52 loc) · 1.87 KB
/
abc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""Abstract base class for argument schema parsers"""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Generic, TYPE_CHECKING, Type, TypeVar
from ..exceptions import CannotParseTypeError
if TYPE_CHECKING:
from ..json_type import JsonType
from typing_extensions import TypeGuard
T = TypeVar("T")
S = TypeVar("S")
class ArgSchemaParser(ABC, Generic[T]):
"""An abstract parser for a specific argument type
Both converts the argument definition to a JSON schema and parses the argument value
from JSON.
"""
def __init__(
self, argtype: Type[T], rec_parsers: list[Type[ArgSchemaParser]]
) -> None:
self.argtype = argtype
self.rec_parsers = rec_parsers
def parse_rec(self, argtype: Type[S]) -> ArgSchemaParser[S]:
"""Parse a type recursively
Args:
argtype (Type[S]): The type to parse
Returns:
ArgSchemaParser[S]: The parser for the type
Raises:
CannotParseTypeError: If the type cannot be parsed
"""
for parser in self.rec_parsers:
if parser.can_parse(argtype):
return parser(argtype, self.rec_parsers)
raise CannotParseTypeError(argtype)
@classmethod
@abstractmethod
def can_parse(cls, argtype: Any) -> TypeGuard[Type[T]]:
"""Whether this parser can parse a specific arg type
Args:
argtype (Any): The type to check
"""
@property
@abstractmethod
def argument_schema(self) -> dict[str, JsonType]:
"""Parse an argument of a specific type"""
@abstractmethod
def parse_value(self, value: JsonType) -> T:
"""Parse a value of a specific type
Args:
value (JsonType): The value to parse
Raises:
BrokenSchemaError: If the value does not match the schema
"""