statham-schema icon indicating copy to clipboard operation
statham-schema copied to clipboard

Create an Object with fields as arguments

Open arthur-proglove opened this issue 5 years ago • 5 comments

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'
}

arthur-proglove avatar Oct 29 '20 09:10 arthur-proglove

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.

jacksmith15 avatar Oct 29 '20 10:10 jacksmith15

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 avatar Oct 29 '20 10:10 arthur-proglove

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.

arthur-proglove avatar Oct 29 '20 10:10 arthur-proglove

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.

jacksmith15 avatar Oct 29 '20 10:10 jacksmith15

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

arthur-proglove avatar Oct 29 '20 12:10 arthur-proglove