[Python-checkins] gh-105578: Add more usage examples to `typing.AnyStr` docs (#107045)

AlexWaygood webhook-mailer at python.org
Mon Jul 31 11:23:13 EDT 2023


https://github.com/python/cpython/commit/f877b32b879f2076bb1c52826af0c28ebf1aaeed
commit: f877b32b879f2076bb1c52826af0c28ebf1aaeed
branch: main
author: Michael The <michael-the1 at users.noreply.github.com>
committer: AlexWaygood <Alex.Waygood at Gmail.com>
date: 2023-07-31T16:23:08+01:00
summary:

gh-105578: Add more usage examples to `typing.AnyStr` docs (#107045)

``typing.AnyStr`` has different semantics to ``str | bytes``, which often leads to user confusion

files:
M Doc/library/typing.rst

diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst
index e2791bbc97b00..539203f1d7136 100644
--- a/Doc/library/typing.rst
+++ b/Doc/library/typing.rst
@@ -849,6 +849,21 @@ using ``[]``.
       concat(b"foo", b"bar")  # OK, output has type 'bytes'
       concat("foo", b"bar")   # Error, cannot mix str and bytes
 
+   Note that, despite its name, ``AnyStr`` has nothing to do with the
+   :class:`Any` type, nor does it mean "any string". In particular, ``AnyStr``
+   and ``str | bytes`` are different from each other and have different use
+   cases::
+
+      # Invalid use of AnyStr:
+      # The type variable is used only once in the function signature,
+      # so cannot be "solved" by the type checker
+      def greet_bad(cond: bool) -> AnyStr:
+          return "hi there!" if cond else b"greetings!"
+
+      # The better way of annotating this function:
+      def greet_proper(cond: bool) -> str | bytes:
+          return "hi there!" if cond else b"greetings!"
+
 .. data:: LiteralString
 
    Special type that includes only literal strings.



More information about the Python-checkins mailing list