mirror of
https://github.com/python/cpython.git
synced 2025-09-27 02:39:58 +00:00
[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 f877b32b87
)
Co-authored-by: Michael The <michael-the1@users.noreply.github.com>
This commit is contained in:
parent
831fd19d30
commit
9f58d9ec90
1 changed files with 15 additions and 0 deletions
|
@ -849,6 +849,21 @@ using ``[]``.
|
||||||
concat(b"foo", b"bar") # OK, output has type 'bytes'
|
concat(b"foo", b"bar") # OK, output has type 'bytes'
|
||||||
concat("foo", b"bar") # Error, cannot mix str and 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
|
.. data:: LiteralString
|
||||||
|
|
||||||
Special type that includes only literal strings.
|
Special type that includes only literal strings.
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue