Request: an AssertingTypeGuard type for TypeGuard-like semantics
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 1.8k
- Forks
- 302
- Avg merge
- 23h
- Merged PRs (30d)
- 8
Description
There is a frequent pattern of TypeGuard-like functions which assert or otherwise raise an exception if a type constraint is not met.
For example, https://github.com/microsoft/pyright/issues/2007 points to a case in which unittest provides assertIsNotNone, but a type-checker cannot infer that type narrowing has occurred. Arguably, the popular typeguard library is based around an implementation of "asserting" type guards. (One which deduces what assertions should be made from the annotations.)
TypeGuards allow for semantics like
y: str
assert is_list_of_str(x)
assert len(x) > 0
y = x[0]
An AssertingTypeGuard would allow for
y: str
assert_is_nonempty_list_of_str(x) # note, this encodes another runtime check, the len check
y = x[0]
This becomes especially valuable if we consider that you might not want to do this all with assert. I may, as an author, prefer my own custom exceptions, e.g.
def assert_is_nonempty_list_of_str(x) -> AssertingTypeGuard[list[str]]:
if not isinstance(x, list):
raise ExpectedListError(x)
if not x:
raise EmptyContainerError(x)
if not all(isinstance(y, str) for y in x):
raise ContainedInvalidTypeError(x, str)
return x
(Apologies if this repo is the wrong place to submit this request/idea. I'm happy to go through another process if necessary.)
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No implementation files or tests are identified in the request. Start by reviewing the TypeGuard examples, the linked Pyright issue, and the typeguard library discussion; determine whether an AssertingTypeGuard belongs in the typing specification and define the expected narrowing and exception semantics before implementation.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- developer-experience
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100