Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested Schema instantiation #87

Open
MattFisher opened this issue Sep 30, 2019 · 0 comments
Open

Nested Schema instantiation #87

MattFisher opened this issue Sep 30, 2019 · 0 comments

Comments

@MattFisher
Copy link

I'm using typesystem to implement a client for an HTTP API, and it's almost perfect for the jobs of constructing payloads to send and parsing payloads that have been received.

The API in question includes nested structures, so I'd like to be able to feed response.json() straight into a schema to get back what's effectively a data class. Using MySchema.validate(payload) works, but it makes the library fragile to changes in the API, like extra options being added to Choice fields that would then cause validation errors on all responses.
MySchema(payload) has the right (liberal) behaviour for flat schemas, but nested structures don't get parsed into the Reference fields:

import typesystem

class MyNestedSchema(typesystem.Schema):
    name = typesystem.String()

class MySchema(typesystem.Schema):
    inner = typesystem.Reference(to=MyNestedSchema)

data = {'nested': {'name': 'My Name'}}

MySchema.validate(data)
# MySchema(nested=MyNestedSchema(name='My Name'))

MySchema(data)
# MySchema(nested={'name': 'My Name'})  # expecting same as previous

Could you explain the reasoning behind the current behaviour of the Schema.__init__ method when passed a single arg?
Would it be possible to instantiate Reference fields in this way? E.g. the current:

for key in self.fields.keys():
	if key in item:
		setattr(self, key, item[key])

could become

for key, schema in self.fields.items():
	if key in item:
		if isinstance(schema, Reference):
			setattr(self, key, schema(item[key]))
		else:
			setattr(self, key, item[key])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant