]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-105578: Add more usage examples to `typing.AnyStr` docs (#107045)
authorMichael The <michael-the1@users.noreply.github.com>
Mon, 31 Jul 2023 15:23:08 +0000 (17:23 +0200)
committerGitHub <noreply@github.com>
Mon, 31 Jul 2023 15:23:08 +0000 (16:23 +0100)
``typing.AnyStr`` has different semantics to ``str | bytes``, which often leads to user confusion

Doc/library/typing.rst

index e2791bbc97b002c7523550660598a9ff410bd0f6..539203f1d713605ca1d9c992d350a792bdeaf0a6 100644 (file)
@@ -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.