typeshed
typeshed copied to clipboard
Incorrect type declaration for `http.server.BaseHTTPRequestHandler.__init__`
The type of the first parameter of http.server.BaseHTTPRequestHandler.__init__ shall be socketserver._RequestType, not bytes.
To fix this issue, simply remove the __init__ method and make BaseHTTPRequestHandler inherit from StreamRequestHandler.
To me, it seems to always be a socket, so _RequestType isn't great either as that would mean it's sometimes tuple[bytes, socket].
Walking backwards through the cpython code:
http.server.BaseHTTPRequestHandlerdoesn't define an__init__method, rather it inherits it fromsocketserver.StreamRequestHandlersocketserver.StreamRequestHandleralso does not define an__init__method, inheriting it fromsocketserver.BaseRequestHandlersocketserver.BaseRequestHandlerdefines the__init__method.
So, with that in mind, looking at socketserver.BaseRequestHandler in typeshed, the signature is defined as:
def __init__(self, request: _RequestType, client_address: _AddressType, server: BaseServer) -> None: ...
The aliases here are defined as follows, while BaseServer is a socketserver class:
_RequestType: TypeAlias = Union[_socket, tuple[bytes, _socket]]
_AddressType: TypeAlias = Union[tuple[str, int], str]
So with this in mind, if we look at the Python page's documentation, the request attribute isn't mentioned in any way:
https://docs.python.org/3/library/http.server.html#http.server.BaseHTTPRequestHandler
This attribute is also not used in any of the defined methods on the BaseHTTPRequestHandler, it is used though in the setup method of the StreamRequestHandler seen here where it gets aliased to self.connection:
https://github.com/python/cpython/blob/main/Lib/socketserver.py#L798
Since this attempts to call instance methods on this value without any form of type checking, I would say this is correctly typed even though it's not necessarily correctly modeled: https://github.com/python/cpython/blob/main/Lib/socketserver.py#L801