Skip to content

Commit 3de42bb

Browse files
[3.11] gh-105578: Add more usage examples to typing.AnyStr docs (GH-107045) (#107504)
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 f877b32) Co-authored-by: Michael The <[email protected]>
1 parent 1b40431 commit 3de42bb

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

Doc/library/typing.rst

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -801,6 +801,21 @@ using ``[]``.
801801
concat(b"foo", b"bar") # OK, output has type 'bytes'
802802
concat("foo", b"bar") # Error, cannot mix str and bytes
803803

804+
Note that, despite its name, ``AnyStr`` has nothing to do with the
805+
:class:`Any` type, nor does it mean "any string". In particular, ``AnyStr``
806+
and ``str | bytes`` are different from each other and have different use
807+
cases::
808+
809+
# Invalid use of AnyStr:
810+
# The type variable is used only once in the function signature,
811+
# so cannot be "solved" by the type checker
812+
def greet_bad(cond: bool) -> AnyStr:
813+
return "hi there!" if cond else b"greetings!"
814+
815+
# The better way of annotating this function:
816+
def greet_proper(cond: bool) -> str | bytes:
817+
return "hi there!" if cond else b"greetings!"
818+
804819
.. data:: LiteralString
805820

806821
Special type that includes only literal strings.

0 commit comments

Comments
 (0)