Tinche / aiofiles

File support for asyncio
Apache License 2.0
2.88k stars 153 forks source link

No overloads for "open" match `str` #180

Closed AutonomousCat closed 9 months ago

AutonomousCat commented 9 months ago

my code

async def read_file(file_path: Path, mode: str = "rb"):
    async with aiofiles.open(file_path, mode) as fp:
        ...

what it shows in VS Code static type checking

No overloads for "open" match the provided arguments
__init__.pyi(87, 5): Overload 5 is the closest match
Argument of type "str" cannot be assigned to parameter "mode" of type "OpenBinaryMode" in function "open"
  Type "str" cannot be assigned to type "OpenBinaryMode"
    "str" cannot be assigned to type "Literal['rb+']"
    "str" cannot be assigned to type "Literal['r+b']"
    "str" cannot be assigned to type "Literal['+rb']"
    "str" cannot be assigned to type "Literal['br+']"
    "str" cannot be assigned to type "Literal['b+r']"
    "str" cannot be assigned to type "Literal['+br']"
    "str" cannot be assigned to type "Literal['wb+']"
  ...PylancereportGeneralTypeIssues
(parameter) mode: str

This gives no type issue with stdlib's open()

Tinche commented 9 months ago

Hello!

You should open this issue over at typeshed (https://github.com/python/typeshed) since that's where the type hints for aiofiles are maintained.

That said, I can see the issue with your type hints. In the read_file function, you're using str as the annotation for mode, but this is incorrect - aiofiles.open(mode=) doesn't take a string, it takes a more specific type: https://github.com/python/typeshed/blob/994d22bfbb542956be24580323d5b4aeef822c77/stdlib/_typeshed/__init__.pyi#L229

I'm not sure what you should do here, so I suggest asking them for best practices here ;)