FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

[3.12] gh-105578: Add more usage examples to `typing.AnyStr` docs (GH-107045) by miss-islington · Pull Request #107503 · python/cpython · GitHub

/ cpython Public
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .rst  (1) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
15 changes: 15 additions & 0 deletions Doc/library/typing.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

Back | FazBrowse Home | New Git URL