gh-105578: Add more usage examples to typing.AnyStr
docs (#107045) · python/cpython@f877b32 (original) (raw)
``` @@ -849,6 +849,21 @@ using []
.
`849`
`849`
` concat(b"foo", b"bar") # OK, output has type 'bytes'
`
`850`
`850`
` concat("foo", b"bar") # Error, cannot mix str and bytes
`
`851`
`851`
``
``
`852`
``` +
Note that, despite its name, ``AnyStr`` has nothing to do with the
``
853
:class:`Any` type, nor does it mean "any string". In particular, ``AnyStr``
``
854
and ``str | bytes`` are different from each other and have different use
``
855
`+
cases::
`
``
856
+
``
857
`+
Invalid use of AnyStr:
`
``
858
`+
The type variable is used only once in the function signature,
`
``
859
`+
so cannot be "solved" by the type checker
`
``
860
`+
def greet_bad(cond: bool) -> AnyStr:
`
``
861
`+
return "hi there!" if cond else b"greetings!"
`
``
862
+
``
863
`+
The better way of annotating this function:
`
``
864
`+
def greet_proper(cond: bool) -> str | bytes:
`
``
865
`+
return "hi there!" if cond else b"greetings!"
`
``
866
+
852
867
`.. data:: LiteralString
`
853
868
``
854
869
` Special type that includes only literal strings.
`