Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-105578: Add more usage examples to typing.AnyStr docs #107045

Merged
merged 5 commits into from
Jul 31, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
AlexWaygood marked this conversation as resolved.
Show resolved Hide resolved

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

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

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

.. data:: LiteralString

Special type that includes only literal strings.
Expand Down