Skip to content

Conversation

@JelleZijlstra
Copy link
Member

@JelleZijlstra JelleZijlstra commented Apr 3, 2024

This adds typing.TypeIs, as proposed in PEP-742.

The runtime implementation is trivial but the documentation is important here. As suggested in the PEP (https://peps.python.org/pep-0742/#how-to-teach-this), I made the documentation emphasize TypeIs over TypeGuard, and the TypeGuard docs now focus on how it is different from TypeIs.


📚 Documentation preview 📚: https://cpython-previews--117517.org.readthedocs.build/


``TypeGuard`` also works with type variables. See :pep:`647` for more details.
``TypeIs`` also works with type variables. For more information, see
PEP 742 (Narrowing types with ``TypeIs``).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same question here as below -- should we link to typing spec instead of PEP?

If we do link to PEP, should probably make it a real link using :pep: role

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding the link for now, we should figure out how to set up intersphinx to enable linking to the spec.

are incompatible (e.g., ``list[object]`` to ``list[int]``) and when the
function does not return ``True`` for all instances of the narrowed type.

Using ``-> TypeIs`` tells the static type checker that for a given
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be clearer to use TypeIs[...] or TypeIs[SomeType] here? The latter would also give you a name that might be clearer/shorter than "the type inside TypeIs" below.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea, done. Also changed the docstrings of TypeGuard and TypeIs accordingly.

JelleZijlstra and others added 2 commits April 8, 2024 22:06
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
@JelleZijlstra JelleZijlstra enabled auto-merge (squash) April 9, 2024 10:18
@JelleZijlstra JelleZijlstra merged commit f2132fc into python:main Apr 9, 2024
diegorusso pushed a commit to diegorusso/cpython that referenced this pull request Apr 17, 2024
See PEP 742.

Co-authored-by: Carl Meyer <carl@oddbird.net>
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants