ID EN
Typing

AnyStr

Python 3.11 🇮🇩 Bahasa Indonesia

Variabel tipe terbatas.

Syntax

PYTHON
typing.AnyStr

Contoh

Example 1
PYTHON
AnyStr = TypeVar('AnyStr', str, bytes)
Example 2
PYTHON
def concat(a: AnyStr, b: AnyStr) -> AnyStr:
    return a + b

concat("foo", "bar")     OK, output has type 'str'
concat(b"foo", b"bar")   OK, output has type 'bytes'
concat("foo", b"bar")    Error, cannot mix str and bytes
Example 3
PYTHON
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!"

See Also

constrained type variable str bytes Any