Tenho o seguinte código:
def from_utf8(string: bytes | str) -> str:
if isinstance(string, bytes):
return string.decode("utf-8")
else:
return string # <- type warning on this line
pylance me dá um aviso de tipo na return string
linha:
Type "bytearray | memoryview[_I@memoryview] | str" is not assignable to return type "str"
Type "bytearray | memoryview[_I@memoryview] | str" is not assignable to type "str"
"bytearray" is not assignable to "str"
Pelo que entendi,
a anotação de tipo x: bytes
é, na verdade, um alias para "tipos de tempo de execução" x: bytes | bytearray | memoryview[_I@memoryview]
, mas isinstance(x, bytes)
verifica apenas bytes
, não os outros dois.
Tentei verificar os tipos ao contrário:
def from_utf8(string: bytes | str) -> str:
if isinstance(string, str):
return string
else:
return string.decode("utf-8") # <- no attribute 'decode' for 'memoryview'
O erro agora é:
Cannot access attribute "decode" for class "memoryview[_I@memoryview]"
Attribute "decode" is unknown
Para contexto:
- meu projeto usa python 3.11
- Vejo esses avisos no vscode, usando o pylance versão 2025.2.1 e
ms-python.python
a extensão python ( ) versão 2025.0.0
Tenho uma maneira conveniente de escrever uma versão from_utf8(string)
que passe no verificador de tipos?
também: minha suposição está correta e está documentada em algum lugar?