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 f877b32

Browse filesBrowse files
authored
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
1 parent f22bf8e commit f877b32
Copy full SHA for f877b32

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
@@ -849,6 +849,21 @@ using ``[]``.
849849
concat(b"foo", b"bar") # OK, output has type 'bytes'
850850
concat("foo", b"bar") # Error, cannot mix str and bytes
851851

852+
Note that, despite its name, ``AnyStr`` has nothing to do with the
853+
:class:`Any` type, nor does it mean "any string". In particular, ``AnyStr``
854+
and ``str | bytes`` are different from each other and have different use
855+
cases::
856+
857+
# Invalid use of AnyStr:
858+
# The type variable is used only once in the function signature,
859+
# so cannot be "solved" by the type checker
860+
def greet_bad(cond: bool) -> AnyStr:
861+
return "hi there!" if cond else b"greetings!"
862+
863+
# The better way of annotating this function:
864+
def greet_proper(cond: bool) -> str | bytes:
865+
return "hi there!" if cond else b"greetings!"
866+
852867
.. data:: LiteralString
853868

854869
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.