Skip to content

idea: use of Thoth.Json.Python with plain classes for runtime type validation  #205

@joprice

Description

@joprice

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions