-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresult.py
More file actions
56 lines (36 loc) · 1.31 KB
/
Copy pathresult.py
File metadata and controls
56 lines (36 loc) · 1.31 KB
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
"""Result type for error handling — replaces error dict anti-pattern.
Uses Pydantic v2 for validation and serialization.
"""
from __future__ import annotations
from typing import Any, Generic, NoReturn, TypeVar
from pydantic import BaseModel, Field
T = TypeVar("T")
class Ok(BaseModel, Generic[T]):
"""Success result."""
value: T
is_ok: bool = Field(default=True, init=False)
is_err: bool = Field(default=False, init=False)
def unwrap(self) -> T:
return self.value
def model_dump(self, **kwargs: Any) -> dict[str, Any]:
"""Override to return just the value for MCP compatibility."""
if isinstance(self.value, BaseModel):
return self.value.model_dump(**kwargs)
if isinstance(self.value, dict):
return self.value
return {"value": self.value}
class Err(BaseModel):
"""Error result."""
error: str
code: str = "error"
is_ok: bool = Field(default=False, init=False)
is_err: bool = Field(default=True, init=False)
def unwrap(self) -> NoReturn:
raise RuntimeError(self.error)
Result = Ok[Any] | Err
def ok(value: T) -> Ok[T]:
"""Create a success result."""
return Ok(value=value)
def err(error: str, code: str = "error") -> Err:
"""Create an error result."""
return Err(error=error, code=code)