typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

Incorrect type declaration for `http.server.BaseHTTPRequestHandler.__init__`

Open iamahuman opened this issue 3 years ago • 2 comments
trafficstars

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.

iamahuman avatar Feb 08 '22 06:02 iamahuman

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].

Akuli avatar Feb 08 '22 09:02 Akuli

Walking backwards through the cpython code:

  1. http.server.BaseHTTPRequestHandler doesn't define an __init__ method, rather it inherits it from socketserver.StreamRequestHandler
  2. socketserver.StreamRequestHandler also does not define an __init__ method, inheriting it from socketserver.BaseRequestHandler
  3. socketserver.BaseRequestHandler defines 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

kkirsche avatar Aug 18 '22 13:08 kkirsche