summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2023-07-31 15:33:00 (GMT)
committerGitHub <noreply@github.com>2023-07-31 15:33:00 (GMT)
commit9f58d9ec9061f1e6ec37432b6031b7c9a580fb6c (patch)
tree66769dd186816bc3fc0e1bd9f4340d957d00c9e4
parent831fd19d30a4051d96117f42b625642ee8a250fb (diff)
downloadcpython-9f58d9ec9061f1e6ec37432b6031b7c9a580fb6c.zip
cpython-9f58d9ec9061f1e6ec37432b6031b7c9a580fb6c.tar.gz
cpython-9f58d9ec9061f1e6ec37432b6031b7c9a580fb6c.tar.bz2
[3.12] gh-105578: Add more usage examples to `typing.AnyStr` docs (GH-107045) (#107503)
gh-105578: Add more usage examples to `typing.AnyStr` docs (GH-107045) ``typing.AnyStr`` has different semantics to ``str | bytes``, which often leads to user confusion (cherry picked from commit f877b32b879f2076bb1c52826af0c28ebf1aaeed) Co-authored-by: Michael The <michael-the1@users.noreply.github.com>
-rw-r--r--Doc/library/typing.rst15
1 files changed, 15 insertions, 0 deletions
diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst
index 11c39a4..60bf06e 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.