Currently, we have str and LiteralStr. These don't do a good job expressing the range of values a string may have. Let's say we have the following function:
Email: TypeAlias=strdefsend_email(email: Email) ->int:
# Send an email
...
# passessend_email("test@example.com")
# passessend_email("badddd")
# passes even if unknown_var is only identified as `str`send_email(unknown_var)
We could improve it by having something like this:
# This is a bad regex pattern, but you get the idea :)Email: TypeAlias=str['[a-z0-9]+@[a-z0-9]+\.[a-z0-9]+']
defsend_email(email: Email) ->int:
# Send an email
...
# passessend_email("test@example.com")
# failssend_email("badddd")
# passes even if unknown_var is only identified as `str`send_email(unknown_var)
A static type checker would be able to validate strings passed in by code. I would imagine this idea can be extended to Pattern and Match generics as well, but I haven't thought too deeply about them yet.
If we don't want to make str generic, we could add a new type to typing called StrPattern. We would need it anyways to backport to typing_extensions.
The text was updated successfully, but these errors were encountered:
The TypeScript feature allows more than type checking though -- IIRC it allows constructing new (string literal) types from other strings.
I personally don't think a feature to let type checkers use regex matching on literals is all that useful -- I'd rather use Email = NewType(str) and leave the validation to runtime code that the type checker doesn't have to be understand. (It's likely that you already have an email validation routine in your system, and it may not be easy to replicate its exact functionality as a regex.)
Fidget-Spinner commentedMay 31, 2022
•
edited
Currently, we have
strandLiteralStr. These don't do a good job expressing the range of values a string may have. Let's say we have the following function:We could improve it by having something like this:
A static type checker would be able to validate strings passed in by code. I would imagine this idea can be extended to
PatternandMatchgenerics as well, but I haven't thought too deeply about them yet.If we don't want to make
strgeneric, we could add a new type to typing calledStrPattern. We would need it anyways to backport to typing_extensions.The text was updated successfully, but these errors were encountered: