Skip to content

Commit

Permalink
gh-105578: Add more usage examples to typing.AnyStr docs (#107045)
Browse files Browse the repository at this point in the history
``typing.AnyStr`` has different semantics to ``str | bytes``, which often leads to user confusion
  • Loading branch information
michael-the1 committed Jul 31, 2023
1 parent f22bf8e commit f877b32
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions Doc/library/typing.rst
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

0 comments on commit f877b32

Please sign in to comment.