Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

codecs._Decoder is incorrectly annotated as taking input: bytes, while at runtime it receives memoryview #10656

Closed
denballakh opened this issue Sep 3, 2023 · 3 comments · Fixed by #12610
Labels
stubs: false positive Type checkers report false errors

Comments

@denballakh
Copy link

denballakh commented Sep 3, 2023

How to check runtime bevahiour:

# main.py
import codecs

def decode(input: bytes, errors: str = 'strict') -> tuple[str, int]:
    print(type(input))
    return '', len(input)

def encode(input: str, errors: str = 'strict') -> tuple[bytes, int]:
    raise NotImplementedError

def search(name: str) -> codecs.CodecInfo | None:
    if name == 'test':
        return codecs.CodecInfo(encode, decode)
    return None

codecs.register(search)
import a

# a.py:
# coding: test
a = 1

When i run this code, decode prints <class 'memoryview'>, which is inconsistent with codecs._Decoder annotation.
Annotating input as memoryview doesnt help, because codecs.CodecInfo accepts only function that takes input arg of type bytes.

@Avasam
Copy link
Collaborator

Avasam commented Sep 5, 2023

Linking #9006 since it relates to potentially incorrect bytes annotation in stdlib.

@srittau srittau added the stubs: false positive Type checkers report false errors label Sep 11, 2023
@srittau
Copy link
Collaborator

srittau commented Sep 11, 2023

PR to fix this welcome!

@Akuli
Copy link
Collaborator

Akuli commented Sep 1, 2024

With #12610, decode functions should be defined like this:

from typing_extensions import Buffer
# alternatively: from collections.abc import Buffer (new in python 3.12)

def decode(input: Buffer, errors: str = 'strict') -> tuple[str, int]:
    # do something with input
    # use bytes(input) or bytearray(input) if needed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stubs: false positive Type checkers report false errors
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants