Extending LiteralString or Literal with structural validation
I actually posted this in python-ideas and I was quickly suggested to come here instead: """ It would be useful to take advantage of the `LiteralString` or `Literal` type hints to add structural validation to literals. For *example*, if these could be subclassed to add a validation method: class MyLiteral(LiteralString): def __validate__(self): ... or extended to allow something like regex in there generic type parameter: Literal[r"\w+"] LiteralString[r"\w+"] then specific kinds of literal string can be "enforced" by static type checkers. Then IDEs could at the very least highlight that a string literal is not valid. I stress these are just examples, the goal is to have a way to tell a static type checker what the structure of a string literal has to be. """
Doesn't `Literal` already accept a regex? https://mypy-play.net/?mypy=latest&python=3.11&gist=d812e3a4c71a04b29ca193ccc2d55f79 I assume you mean that you want the type checker to accept "any string that matches this regex"? Having a `__validate__` method seems to get too deep into runtime type checking IMO. We discussed this sort of thing a bit at https://github.com/annotated-types/annotated-types . I think we concluded that it would be great if type checkers wanted to expand to support something like `AnyWord = Annotated[str, Pattern(r"\w+")]` because it'd be opt-in: type checkers that don't understand that specific annotation just ignore it and accept any string. Otherwise you run into issues when you inevitably want to do more complex validation like greater than / less then because it get clunky to pass in multiple generic type variables, have defaults for them, etc.
Adrian Garcia Badaracco wrote:
Doesn't `Literal` already accept a regex? https://mypy-play.net/?mypy=latest&python=3.11&gist=d812e3a4c71a04b2...
I guess so, but doesn't that regex mean the string should be that literal value rather than be a string that matches that regex? That is why it would be nice for LiteralString to be what is extended instead, or some other LiteralRegex generic?
I assume you mean that you want the type checker to accept "any string that matches this regex"?
Yes, that's the goal.
Having a `__validate__` method seems to get too deep into runtime type checking IMO. Yes, I agree.
participants (2)
-
Adrian Garcia Badaracco
-
Mathew Elman