jacksmith15 / statham-schema

Statham is a Python Model Parsing Library for JSON Schema.
https://statham-schema.readthedocs.io/en/latest/
MIT License
38 stars 11 forks source link

Create an Object with fields as arguments #79

Open arthur-proglove opened 3 years ago

arthur-proglove commented 3 years ago

It would be nice to be able to instantiate a model with some fields the same way a dataclass can be created and be able to use it to output a JSON dict.

class MySuperModel(Object):
    some_field: str = Property(String(enum=['foo', 'bar', 'baz']), required=True)

s = MySuperModel(some_field='foo')
print(s)

{
    'some_field': 'foo'
}
jacksmith15 commented 3 years ago

I don't intend to add support for keyword arguments as the fields. Is there anything this prevents you from doing? If you replace some_field="foo" in the above example with dict(some_field="foo") then you can instantiate your model.

Instance conversion to a dictionary is a different story - if you could open a separate issue for that I would be grateful.

arthur-proglove commented 3 years ago

Yeah, this is what I am doing for now, I create my object this way

MySuperModel({'some_field': 'foo'})

which is basically the same as you propose, it works but I found it less convenient as using arguments, especially for nested objects.

I find this easier to instantiate to avoid errors at runtime and sport them with a linter:

MySuperModel(
   some_field='foo',
   nested_object=NestedObject(some_other_field='bar')
)

than this:

MySuperModel({
   'some_field': 'foo',
   'nested_object': {
    'some_other_field': 'bar'
  }
})
arthur-proglove commented 3 years ago

Regarding the conversion to a dictionary it's anyway not an issue for now as converting a dict to json is fairly easy :-) since the Object is anyway created from a dict already.

jacksmith15 commented 3 years ago

I'm afraid even if the arguments were keyword arguments, I still don't think a linter could detect an issue there. If you can suggest a way to do that, I would certainly consider it.

The problem is signalling to a linter/static type checker: 1) which arguments are allowed from properties 2) which arguments are allowed via patternProperties 3) whether additional properties are allowed

And all of the other variations supported by the JSON Schema spec.

arthur-proglove commented 3 years ago

I agree with you it's an easy task, I'm not able to provide a solution here.