Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 3de42bb

Browse filesBrowse 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 <michael-the1@users.noreply.github.com>
1 parent 1b40431 commit 3de42bb
Copy full SHA for 3de42bb

File tree

1 file changed

+15
-0
lines changed
Filter options

1 file changed

+15
-0
lines changed

‎Doc/library/typing.rst

Copy file name to clipboardExpand all lines: Doc/library/typing.rst
+15Lines 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 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.