-
-
Notifications
You must be signed in to change notification settings - Fork 42
Open
Description
In js, I have made use of the fromValue as a form of "runtime type validation" similar to how zod is used in ts using anonymous records. I found that something similar can be done with classes with a dict member and dataclasses by providing a separate instance of IDecoderHelpers toDecode.Advanced.fromValue with a few overrides:
...
member _.isObject jsonValue =
pyInstanceof jsonValue pyDict
|| hasattr (jsonValue, "__dict__")
|| hasattr (jsonValue, "__dataclass_fields__")
member _.hasProperty fieldName jsonValue =
if hasattr (jsonValue, "__dataclass_fields__") then
emitPyStatement (jsonValue, fieldName) "return $1 in $0.__dataclass_fields__"
else
emitPyStatement (jsonValue, fieldName) "return $1 in $0"
member _.getProperties jsonValue =
emitPyStatement
jsonValue
"""
if hasattr($0, "__dataclass_fields__"):
return $0.__dataclass_fields__.keys()
if hasattr($0, "__dict__"):
return $0.__dict__.keys()
return $0.keys()
"""
member _.getProperty(fieldName: string, jsonValue: obj) =
emitPyStatement (jsonValue, fieldName) "return $0.__getattribute__($1)"
...This could be useful for wrapping interfaces like argparse when using subcommands, where each command has a callback that takes an object, or perhaps some event listening interfaces that respond with similar arbitrary data objects.
Metadata
Metadata
Assignees
Labels
No labels