schema icon indicating copy to clipboard operation
schema copied to clipboard

Feature request: Typings interop

Open warrenronsiek opened this issue 5 years ago • 3 comments

It would be really cool if you could use defined schemas as types. E.g.:

s = Schema({'x': int, 'y': str})
xy: s.type = {'x': 4, 'y':'a'}

I find myself defining Schemas to validate http responses in tests, but once they are defined, I would like to use them to provide type hints to my IDE. However, ATM I have to define a different type using either Typings or a dataclass in order to do so. This leads to code duplication where I have to define datatypes for type hints that are exact clones of the Schemas used in validation. This is bad.

It would be much better to have a schema.to_dataclass or schema.type method to extract a dataclass or type. Even better if these methods would be called implicity when schemas are used as types.

warrenronsiek avatar Jan 14 '20 20:01 warrenronsiek

+1 on that feature. Type-hints are a good practice in python, as it aims to write documented code.

cl-parsons avatar Nov 30 '21 14:11 cl-parsons

One should also be able to use types as schemas.

Python 3.8 also has TypedDict:

class S(TypedDict):
    x: int
    y: str

xy: S = {'x': 4, 'y':'a'}

Schema(S).validate(xy)

Or some function to use get_type_hints on a value and validate from that.

pydantic seems close.

kohtala avatar Apr 06 '22 09:04 kohtala

I just tried the library for the first time, it works as expected but I agree that it makes no sense to have both a type and a schema that describe the exact same thing.

In my opinion @kohtala 's proposition looks more interesting because people already have types declared in their backend and they could use your validation tool without having to rewrite any code.

cglacet avatar Oct 21 '22 09:10 cglacet