Page 1 of 1

Wie können Sie dem typechecker für a '(Bytes | str) -> str' Funktion richtig gefallen?

Posted: 14 Feb 2025, 08:17
by Anonymous
Ich habe den folgenden Code: < /p>

Code: Select all

def from_utf8(string: bytes | str) -> str:
if isinstance(string, bytes):
return string.decode("utf-8")
else:
return string  # 
Mein Verständnis ist:

Die Annotation von Typ: Bytes < /code> ist tatsächlich ein Alias ​​für "Laufzeittypen" x: Bytes | Bytearray | majoreView [_i@meserationView] 
, aber isinstance (x, bytes) prüft nur Bytes , nicht die beiden anderen.
Ich habe versucht Für Typen umgekehrt: < /p>

Code: Select all

def from_utf8(string: bytes | str) -> str:
if isinstance(string, str):
return string
else:
return string.decode("utf-8")  # 
Der Fehler wird nun: < /p>
Cannot access attribute "decode" for class "memoryview[_I@memoryview]"
  Attribute "decode" is unknown
< /code>
Wenn das relevant ist: Mein Projekt verwendet Python 3.11. von from_utf8 (String) 
, der den Typ -Checker übergibt?>