11from pydantic import BaseModel
2- from typing import Any , Type
2+ from typing import Any , Type , Protocol
33from pydantic import GetCoreSchemaHandler
44from pydantic_core import CoreSchema , core_schema
55
@@ -8,9 +8,9 @@ class ID(str):
88 """A custom scalar for IDs. If passed a pydantic model it an id property
99 it will automatically validate to that models id"""
1010
11- def __init__ (self , value : str ) -> None :
12- """Initialize the ID"""
13- self . value = value
11+ def __get__ (self , instance , owner ) -> "ID" : ...
12+
13+ def __set__ ( self , instance , value : "IDCoercible" ) -> None : ...
1414
1515 @classmethod
1616 def __get_pydantic_core_schema__ (
@@ -22,7 +22,7 @@ def __get_pydantic_core_schema__(
2222 return core_schema .no_info_before_validator_function (cls .validate , handler (str ))
2323
2424 @classmethod
25- def validate (cls : Type ["ID" ], v : Any ) -> "ID" :
25+ def validate (cls : Type ["ID" ], v : "IDCoercible" ) -> "ID" :
2626 """Validate the ID"""
2727 if isinstance (v , BaseModel ):
2828 if hasattr (v , "id" ):
@@ -36,4 +36,13 @@ def validate(cls: Type["ID"], v: Any) -> "ID":
3636 if isinstance (v , int ):
3737 return cls (str (v ))
3838
39- raise TypeError (f"Needs to be either a instance of BaseModel (with an id) or a string got { type (v )} " )
39+ raise TypeError (
40+ f"Needs to be either a instance of BaseModel (with an id) or a string got { type (v )} "
41+ )
42+
43+
44+ class WithId (Protocol ):
45+ id : ID
46+
47+
48+ IDCoercible = str | ID | WithId
0 commit comments