Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PEP 724: Stricter TypeGuard #3266

Merged
merged 83 commits into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from 47 commits
Commits
Show all changes
83 commits
Select commit Hold shift + click to select a range
f5205c6
Update after Erik's feedback
rchiodo Aug 2, 2023
9da9233
Erik's initial comments
rchiodo Aug 2, 2023
00d5247
Update after Erik's feedback
rchiodo Aug 2, 2023
79720d5
Merge branch 'rchiodo/pep-722-strictertypeguard' of https://github.co…
rchiodo Aug 2, 2023
4c4a0e9
Update pep-0722.rst
rchiodo Aug 3, 2023
4f90e9c
Add the deliberate mistake case
rchiodo Aug 3, 2023
faa5768
Merge branch 'rchiodo/pep-722-strictertypeguard' of https://github.co…
rchiodo Aug 3, 2023
f00e7a2
Update pep-0722.rst
rchiodo Aug 3, 2023
c895a0a
Update pep-0722.rst
rchiodo Aug 3, 2023
5305af4
Update pep-0722.rst
rchiodo Aug 3, 2023
b6335f0
Update pep-0722.rst
rchiodo Aug 3, 2023
f24ca7c
Update pep-0722.rst
rchiodo Aug 3, 2023
cbf907a
More review feedback
rchiodo Aug 3, 2023
dea607f
Merge branch 'rchiodo/pep-722-strictertypeguard' of https://github.co…
rchiodo Aug 3, 2023
e5a71ea
More review feedback
rchiodo Aug 3, 2023
a32efa4
Fix 80 column limit
rchiodo Aug 3, 2023
708f60c
Update pep-0722.rst
rchiodo Aug 3, 2023
662341f
Update pep-0722.rst
rchiodo Aug 3, 2023
24b88ba
More feedback
rchiodo Aug 3, 2023
a682219
Review feedback
rchiodo Aug 3, 2023
6287be5
Some more subtle word changes
rchiodo Aug 3, 2023
a2e0b22
Change verbiage a little more
rchiodo Aug 3, 2023
66bdf14
Merge pull request #1 from rchiodo/rchiodo/pep-722-strictertypeguard
rchiodo Aug 4, 2023
5850d66
Change pep number
rchiodo Aug 4, 2023
31fb9c7
Merge branch 'rchiodo/pep-722' of https://github.com/rchiodo/peps int…
rchiodo Aug 4, 2023
641b761
Update PEP number
rchiodo Aug 4, 2023
1ec2207
Fix some errors in the pre-commit
rchiodo Aug 4, 2023
ce63130
Merge branch 'main' into rchiodo/pep_725
rchiodo Aug 4, 2023
6184c24
Review feedback
rchiodo Aug 4, 2023
00e028c
Merge branch 'rchiodo/pep_725' of https://github.com/rchiodo/peps int…
rchiodo Aug 4, 2023
7ab28d9
Update codeowners
rchiodo Aug 4, 2023
dddc7cb
Remove ``Resolution``
AA-Turner Aug 4, 2023
7e51159
Move to specification
rchiodo Aug 4, 2023
68e73a3
Merge branch 'rchiodo/pep_725' of https://github.com/rchiodo/peps int…
rchiodo Aug 4, 2023
a9b0407
Update pep-0724.rst
rchiodo Aug 4, 2023
106f10a
Formatting and grammar
rchiodo Aug 4, 2023
e44d060
Merge branch 'rchiodo/pep_725' of https://github.com/rchiodo/peps int…
rchiodo Aug 4, 2023
07af8f7
Update pep-0724.rst
rchiodo Aug 4, 2023
81bc56c
More review feedback
rchiodo Aug 4, 2023
535ab81
Fix footnotes
rchiodo Aug 4, 2023
7b69948
Update based on Eric's feedback
rchiodo Aug 4, 2023
ddc4ec3
Fix build warnings
rchiodo Aug 4, 2023
dd4bf80
Fixup comment
rchiodo Aug 4, 2023
5eab931
Add some more examples
rchiodo Aug 5, 2023
c5449b8
Rework 'backwards compatibility'
rchiodo Aug 5, 2023
6ff5be9
Grammar
rchiodo Aug 5, 2023
487a47e
Remove ``Resolution``
AA-Turner Aug 5, 2023
4f9753a
Update pep-0724.rst
rchiodo Aug 7, 2023
3c37ec3
Update pep-0724.rst
rchiodo Aug 7, 2023
27bac54
Merge branch 'main' into rchiodo/pep_725
rchiodo Aug 7, 2023
b90df2c
Fix column width
rchiodo Aug 7, 2023
3263b63
Another try for backwards compatibility
rchiodo Aug 8, 2023
dcf3d49
another blurb about backwards compatibility
rchiodo Aug 8, 2023
598d0da
Merge remote-tracking branch 'upstream/main' into rchiodo/pep_725
rchiodo Aug 25, 2023
a580f4a
Add mypy primer test
rchiodo Aug 25, 2023
95d4616
Add another rejected idea
rchiodo Aug 25, 2023
b267456
Fix typo
rchiodo Aug 28, 2023
6b246f2
Update based on discussions with Eric
rchiodo Aug 30, 2023
0e24a6f
Remove unnecessary lines and incorrect statement about covariance
rchiodo Aug 31, 2023
457ea0e
Merge branch 'main' into rchiodo/pep_725
rchiodo Aug 31, 2023
5ff0408
Use 'math' to specify logic
rchiodo Sep 1, 2023
b91a5ca
Merge branch 'main' into rchiodo/pep_725
rchiodo Sep 1, 2023
d8ea2cc
Don't reference intersections as a future PEP
rchiodo Sep 1, 2023
671df1f
Extra line
rchiodo Sep 1, 2023
d3048de
Improve wording
rchiodo Sep 1, 2023
4a7039e
Move degenerate case
rchiodo Sep 5, 2023
e3fd558
Some formatting
rchiodo Sep 5, 2023
bccb5fb
Merge branch 'main' into rchiodo/pep_725
rchiodo Sep 5, 2023
e5f4749
Update pep-0724.rst
JelleZijlstra Sep 8, 2023
25fc119
Merge remote-tracking branch 'upstream/main' into rchiodo/pep_725
AA-Turner Sep 9, 2023
44a31ae
Move to ``peps/``
AA-Turner Sep 9, 2023
93b1503
Whitespace
AA-Turner Sep 9, 2023
499639f
Add trailing comma
AA-Turner Sep 9, 2023
b181ef9
Copyright formatting
AA-Turner Sep 9, 2023
5963e45
Update peps/pep-0724.rst
rchiodo Sep 11, 2023
867c541
Update peps/pep-0724.rst
rchiodo Sep 11, 2023
2a2336a
Update peps/pep-0724.rst
rchiodo Sep 11, 2023
dd5fdee
More review feedback
rchiodo Sep 11, 2023
92768e2
Updates from Eric Traut
rchiodo Sep 15, 2023
159c519
Fix build and linter
rchiodo Sep 15, 2023
8f28e7a
Merge branch 'main' into rchiodo/pep_725
rchiodo Sep 15, 2023
678ce5f
Try fixing post history
rchiodo Sep 15, 2023
f817e07
Fix post history again
rchiodo Sep 15, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,7 @@ pep-0719.rst @Yhg1s
pep-0720.rst @FFY00
pep-0721.rst @encukou
pep-0722.rst @pfmoore
pep-0724.rst @jellezijlstra
# ...
# pep-0754.txt
# ...
Expand Down
238 changes: 238 additions & 0 deletions pep-0724.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
PEP: 724
Title: Stricter Type Guards
Author: Rich Chiodo <rchiodo at microsoft.com>,
Eric Traut <erictr at microsoft.com>,
Erik De Bonte <erikd at microsoft.com>
Sponsor: Jelle Zijlstra <[email protected]>
Discussions-To: https://mail.python.org/archives/list/[email protected]/thread/EMUD2D424OI53DCWQ4H5L6SJD2IXBHUL/
Status: Draft
Type: Standards Track
Topic: Typing
Content-Type: text/x-rst
Created: 28-Jul-2023
Python-Version: 3.13
Post-History:


Abstract
========

:pep:`647` introduced the concept of ``TypeGuard`` functions which return
``True`` if their input parameter matches their target type. For example, a
function that returns ``TypeGuard[str]`` is assumed to return ``True`` if and
only if its input parameter is a ``str``. This allows type checkers to narrow
types when a ``TypeGuard`` function returns ``True``.

This PEP further refines :pep:`647` by allowing type checkers to also narrow
types when a ``TypeGuard`` function returns ``False``.

Motivation
==========

``TypeGuards`` are used throughout Python libraries to allow a type checker to
rchiodo marked this conversation as resolved.
Show resolved Hide resolved
narrow the type of something when the ``TypeGuard`` returns ``True``.

However, in the ``False`` case, :pep:`647` doesn't prescribe what the type
might be:

.. code-block:: python

def is_str(val: str | int) -> TypeGuard[str]:
return isinstance(val, str)

def func(val: str | int):
if is_str(val):
# Type checkers can assume val is a 'str' in this branch
else:
# Type here is not narrowed. It is still 'str | int'


Specification
=============

This PEP proposes some modifications to :pep:`647` in order to allow a type
checker to further narrow what a ``TypeGuard`` is indicating when it returns
``False``.

* When the output type of a ``TypeGuard`` is consistent [#isconsistent]_ with
the type of its first input parameter, type checkers will apply stricter type
semantics:

.. code-block:: python

# Stricter TypeGuard possible (Kangaroo | Koala is consistent with Animal)
def is_marsupial(val: Animal) -> TypeGuard[Kangaroo | Koala]:
return isinstance(val, Kangaroo | Koala)

# Stricter TypeGuard not possible (list[T] is not consistent with
# list[T | None])
def has_no_nones(val: list[T | None]) -> TypeGuard[list[T]]:
return None not in val

* When stricter semantics are possible, the output type for the ``False`` case
can be determined:

.. code-block:: python

def is_str(val: str | int) -> TypeGuard[str]: # Stricter mode possible
return isinstance(val, str)

def func(val: str | int):
if is_str(val):
# Type checkers can assume val is a 'str' in this branch
else:
# Type checkers can assume val is an 'int' in this branch

* When the output type of the ``TypeGuard`` is a union, the type checker can
apply additional type narrowing based on the type of the first input
argument, eliminating union elements that are impossible given the input
argument type:

.. code-block:: python

def is_cardinal_direction(val: str) -> TypeGuard[Literal["N", "S", "E", "W"]]:
return val in ("N", "S", "E", "W")

def func(direction: Literal["NW", "E"]):
if is_cardinal_direction(direction):
# Literal["E"] The type cannot be "N", "S" or "W" here because of
# argument type
else:
# Literal["NW"]

Additional Examples
===================

Any
---

``Any`` is consistent [#isconsistent]_ with any other type, which means
stricter semantics can be applied.

.. code-block:: python

def is_a(x: Any) -> TypeGuard[A]: # Stricter TypeGuard possible
return isinstance(x, A)

def test(x: A | B):
if is_a(x):
# x is of type A here
else:
# x is of type B here

Covariance
----------

Covariance is not the same thing as being consistent [#isconsistent]_:

.. code-block:: python

def is_str_seq(val: Sequence[str | int]) -> TypeGuard[Sequence[str]]:
return all(isinstance(x, str) for x in val)

def func3(val: Sequence[str | int]):
if is_str_seq(val):
# val is Sequence[str]
else:
# val is Sequence[str | int]

Type ``B`` is consistent [#isconsistent]_ with type ``A`` if

* ``B`` is a subtype of ``A``
* ``A`` is Any
* ``B`` is Any

``Sequence[str]`` is not a subtype of ``Sequence[str | int]`` so the special
semantics cannot be applied and only the ``True`` case is narrowed.

Degenerate case
---------------

It is possible to break the type checker by making a ``TypeGuard`` that is
incorrect:

.. code-block:: python

def is_positive_int(val: int | str) -> TypeGuard[int]:
return isinstance(val, int) and val > 0

def func(val: int | str):
if is_positive_int(val):
# Type checker assumes int here
else:
# Type checker assumes str incorrectly here

As :pep:`647 <647#enforcing-strict-narrowing>` stated, users can create invalid
JelleZijlstra marked this conversation as resolved.
Show resolved Hide resolved
``TypeGuards``. The same thing applies to this PEP. If the user is not careful
rchiodo marked this conversation as resolved.
Show resolved Hide resolved
the type checker may flag things incorrectly.

Backwards Compatibility
=======================

The new ``False`` case for a ``TypeGuard`` breaks backwards compatibility.

.. code-block:: python

def is_int(val: int | str) -> TypeGuard[int]:
return isinstance(val, int)

def func(val: int | str):
if is_int(val):
# Type checker assumes int here
else:
# Type checker assumes str here

A type checker will assume in the ``False`` case that the value is ``str``.

This is a change in behavior from :pep:`647`.

TBD: Not sure what the resolution of this should be yet. I want to say
something like - Code that already exists would not be harmed by this change as
existing code would have more checks to validate the type on the else case. For
new code, the assumption is that users will expect this behavior anyway.


How to Teach This
=================

We assert that users unfamiliar with ``TypeGuard`` will expect the behavior
outlined in this PEP, therefore making ``TypeGuard`` easier to teach and
explain.


Reference Implementation
========================

A reference `implementation`__ of this idea exists in Pyright.

__ https://github.com/microsoft/pyright/commit/9a5af798d726bd0612cebee7223676c39cf0b9b0


Rejected Ideas
==============

Originally a new ``StrictTypeGuard`` construct was proposed. A
``StrictTypeGuard`` would be similar to to a ``TypeGuard`` except it would
explicitly state that output type was consistent [#isconsistent]_ with the
input type. Type checkers would validate that the output type was consistent
[#isconsistent]_ with the input type.

See this comment: `StrictTypeGuard proposal`__

__ https://github.com/python/typing/discussions/1013#discussioncomment-1966238

This was rejected because for most cases it's not necessary. Most people assume
when the ``TypeGuard`` returns ``False``, that the input type has been narrowed
to its other type. Why not just change the specification to match their
assumptions?

Footnotes
=========

.. [#isconsistent] :pep:`PEP 483's discussion of is-consistent <483#summary-of-gradual-typing>`

Copyright
=========

This document is placed in the public domain or under the CC0-1.0-Universal
license, whichever is more permissive.