Make schema work for Literal and NewType #649
@@ Coverage Diff @@ ## master #649 +/- ## ===================================== Coverage 100% 100% ===================================== Files 15 15 Lines 2651 2671 +20 Branches 524 529 +5 ===================================== + Hits 2651 2671 +20
@samuelcolvin I think the discussion of the proper schema to use for Literal has been resolved.
I'm keen to get this merged because, while I have a workaround I'm happy with for now for non-UUID types, the workaround for uuid.UUID-based NewTypes is currently a little more painful (I describe this in more detail below).
If it would make it easier for you to review, I would be happy to split this into two pull requests (one for NewType and one for Literal). I would just like to get the NewType fix into a release as soon as possible, as it will allow me to remove a decent amount of cruft from my code.
For most types involved with NewType (e.g., str, int, etc.),
if TYPE_CHECKING: MyLabel = NewType("MyLabel", str) else: MyLabel = str
This way, type checking works properly, and if I use the "NewType" as a field label, it is interpreted correctly by pydantic. This results in a little more runtime overhead than NewType, but at least everything works properly.
if TYPE_CHECKING: MyID = NewType("MyID", uuid.UUID) else: MyID = uuid.UUID random_id: MyID = uuid.UUID(uuid4_str()) # type: ignore
However, needing to create a local variable for this every time is starting to pollute my code, and worse, mypy can't notify me if I forget to avoid casting uuids to the typed variant (leading to annoying runtime errors).
I'm happy with this.
Sorry I've been absent in this conversation, I was at pycon europe, then at a friends wedding the sorting the rest of my life out.
I'll try to put some time into pydantic later in the week to get this and other PRs merged and released and work out what to do about v1.