PEP647 typing.TypeGuard based is_ok() and is_err() helpers
See original GitHub issuePEP 647 (https://www.python.org/dev/peps/pep-0647/) makes it possible to write custom type guard functions.
this makes it possible to write shorthand is_ok(...)
and is_err(...)
functions that effectively work as shorthands for the longer isinstance(..., ...)
forms, resulting in denser and more readable code, while still keeping all the benefits of strict type checking:
def is_ok(result: Result[T, E]) -> TypeGuard[Ok[T]]:
return isinstance(result, Ok)
def is_err(result: Result[T, E]) -> TypeGuard[Err[E]]:
return isinstance(result, Err)
not all supported python versions support TypeGuard
, but the widely used typing_extensions
package (https://github.com/python/typing/blob/master/typing_extensions/README.rst) has a functional backport that works with (at least) mypy. i personally do not see a problem adding a dependency on typing_extensions
, since it’s maintained ‘upstream’, close to python itself, and it will already be pulled in by many other libraries in many real-world applications.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:4
- Comments:7 (4 by maintainers)
It seems like mypy generic typeguards are fixed, but there’s still no negation.
Doing something like this would work:
…but ideally we wouldn’t need to do this.
Related discussion for typeguard negations: https://github.com/python/typing/discussions/1013
If only older Python versions need it, I don’t think adding a dependency is a problem. By upgrading your Python, you can get rid of the dependency.
We did the same thing with
typing
when we still supported Python versions that didn’t have this built-in yet.From my experience with TS, type guards are pretty nice to have.