hypercorn icon indicating copy to clipboard operation
hypercorn copied to clipboard

Config typing as a Protocol

Open LucidDan opened this issue 3 years ago • 1 comments

The typing support in the Config class is really useful, as it makes it possible to get autocompletion when creating config objects- saves some time on looking up documentation, and helps avoid typo and formatting errors, and other silly mistakes.

However, if you're trying to load configs using from_object() or --config "python:", you can't use a Config() instance (it does not work, as there are properties and other methods on the Config class, not just the configuration attributes, and it tries to copy all of them over).

It'd be really useful if there was typing support to provide a way to identify an object as a hypercorn config object. I imagine it being something like this:

from hypercorn.typing import ConfigType  
# where ConfigType is a protocol defining the allowed config attributes and their types


# Ex.1: A class that implements the ConfigType protocol
class MyConfig(ConfigType):
    bind = ["127.0.0.1:8000", ]

cfg = MyConfig()


# Ex.2: A generic object that implements the protocol
cfg: ConfigType = object()
cfg.bind = ["127.0.0.1:8000", ]


# Ex.3: A module that implements the protocol
# Making a module that implements a Protocol is also possible (relatively recent addition to mypy and pyright) ...
# I'm not sure how you would type-check this, but I imagine it would require some variation on:

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    # we don't use the module 'my_config.py' in code, only in the CLI, but we still want to type-check it...
    import my_config
    cfg: ConfigType = my_config  # will complain if the module doesn't comply with the ConfigType protocol

Since you're already using typing-extensions, using a Protocol even on python 3.7 shouldn't be an issue, I think, as it includes backport support for it.

Does this approach seem reasonable? Happy to put together a PR if its worth the time.

LucidDan avatar Sep 04 '22 03:09 LucidDan

Maybe an ABC would make more sense - I think there are things we would want to check at runtime for the config to be valid.

pgjones avatar Sep 26 '22 20:09 pgjones