Annotate pycurl's getinfo() and getinfo_raw()#14929
Conversation
getinfo and getinfo_raw docs: http://pycurl.io/docs/latest/curlobject.html#pycurl.Curl.getinfo
This comment has been minimized.
This comment has been minimized.
|
As the primer output shows, this is problematic, as the user needs to add an instance check, even though the return type is usually statically known. A better approach would be to add overloads for the various |
|
getinfo takes a single integer argument and the return values have different types depending on the argument's value. Is it possible to use @overload to match specific constant values of a function's argument? |
|
Ah, looks like something this might work: from typing import Literal, overload
@overload
def foo(x: Literal[1]) -> int:
...
@overload
def foo(x: Literal[2]) -> str:
...
def foo(x: int):
if x == 1:
return 1
if x == 2:
return "world"
print(1 + foo(1))
print("hello " + foo(2))I'll see if can use something similar in the PR. |
|
The only way I've found to work so far is quite messy. In pycurl.pyi: class Curl:
[...]
@overload
def getinfo(self, info: Literal[1048577]) -> str: ...
@overload
def getinfo(self, info: Literal[2097154]) -> int: ...
@overload
def getinfo(self, info: Literal[4194338]) -> list[Sequence[tuple[str, str]]]: ...
@overload
def getinfo(self, info: int): ...
[...]In client code: import pycurl
c = pycurl.Curl()
reveal_type(c.getinfo(pycurl.EFFECTIVE_URL)) # mypy reveals: builtins.str
reveal_type(c.getinfo(pycurl.RESPONSE_CODE)) # mypy reveals: builtins.int
reveal_type(c.getinfo(pycurl.INFO_CERTINFO)) # mypy reveals: builtins.list[typing.Sequence[tuple[builtins.str, builtins.str]]]The messy part is that I cannot use the existing pycurl constants ( I tried a few different things like: @overload
def getinfo(self, info: Literal[pycurl.EFFECTIVE_URL]) -> str: ...and: EFFECTIVE_URL: Literal[1048577] = 1048577
@overload
def getinfo(self, info: EFFECTIVE_URL) -> str: ...but neither worked with mypy. |
|
I didn't realize the constants were this messy. In that case, I don't think we should overloads like I suggested, but instead we should use |
|
According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉 |
getinfo and getinfo_raw docs: http://pycurl.io/docs/latest/curlobject.html#pycurl.Curl.getinfo