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

Post a reply

Smilies
:) :( :oops: :chelo: :roll: :wink: :muza: :sorry: :angel: :read: *x) :clever:
View more smilies

BBCode is ON
[img] is ON
[flash] is OFF
[url] is ON
Smilies are ON

Topic review
   

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

by Anonymous » 14 Feb 2025, 08:17

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?>

Top