Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add more usage examples to typing.AnyStr
  • Loading branch information
michael-the1 committed Jul 22, 2023
commit a3be84bc956a4c9b6952d2c7c0635ce9b24f3609
16 changes: 16 additions & 0 deletions Doc/library/typing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,22 @@ using ``[]``.
concat(b"foo", b"bar") # OK, output has type 'bytes'
concat("foo", b"bar") # Error, cannot mix str and bytes

Note that ``AnyStr`` and ``str | bytes`` are different from each other and
have different use cases. ``str | bytes`` does allow you to mix str and bytes::

def concat(a: str | bytes, b: str | bytes) -> str | bytes:
return a + b

concat("foo", b"bar") # Passes typecheck but raises an error at runtime
Comment thread
AlexWaygood marked this conversation as resolved.
Outdated

As a type variable, ``AnyStr`` is only used if it's at least part of the input arguments::
Comment thread
AlexWaygood marked this conversation as resolved.
Outdated

def greet_bad(cond: bool) -> AnyStr:
return "hi there!" if cond else b"greetings!" # Error
Comment thread
michael-the1 marked this conversation as resolved.
Outdated

def greet_proper(cond: bool) -> str | bytes:
return "hi there!" if cond else b"greetings!" # OK
Comment thread
michael-the1 marked this conversation as resolved.
Outdated

.. data:: LiteralString

Special type that includes only literal strings.
Expand Down