Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add typing information #1289

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 53 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ testing = [
linting = [
"ruff>=0.8.0,<1",
"mypy>=1.13.0,<2",
"typing_extensions>=4.12.2",
]

packaging = [
Expand All @@ -90,8 +91,58 @@ h2 = [ "py.typed" ]
version = { attr = "h2.__version__" }

[tool.ruff]
line-length = 140
line-length = 150
target-version = "py39"
format.preview = true
format.docstring-code-line-length = 100
format.docstring-code-format = true
lint.select = [
"ALL",
]
lint.ignore = [
"PYI034", # PEP 673 not yet available in Python 3.9 - only in 3.11+
"ANN001", # args with typing.Any
"ANN002", # args with typing.Any
"ANN003", # kwargs with typing.Any
"ANN401", # kwargs with typing.Any
"SLF001", # implementation detail
"CPY", # not required
"D101", # docs readability
"D102", # docs readability
"D105", # docs readability
"D107", # docs readability
"D200", # docs readability
"D205", # docs readability
"D205", # docs readability
"D203", # docs readability
"D212", # docs readability
"D400", # docs readability
"D401", # docs readability
"D415", # docs readability
"PLR2004", # readability
"SIM108", # readability
"RUF012", # readability
"FBT001", # readability
"FBT002", # readability
"PGH003", # readability
"PGH004", # readability
"FIX001", # readability
"FIX002", # readability
"TD001", # readability
"TD002", # readability
"TD003", # readability
"S101", # readability
"PD901", # readability
"ERA001", # readability
"ARG001", # readability
"ARG002", # readability
"PLR0913", # readability
]
lint.isort.required-imports = [ "from __future__ import annotations" ]

[tool.mypy]
show_error_codes = true
strict = true

[tool.pytest.ini_options]
testpaths = [ "tests" ]
Expand Down Expand Up @@ -150,7 +201,7 @@ commands = [
dependency_groups = ["linting"]
commands = [
["ruff", "check", "src/"],
# TODO: ["mypy", "src/"],
["mypy", "src/"],
]

[tool.tox.env.docs]
Expand Down
5 changes: 3 additions & 2 deletions src/h2/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# -*- coding: utf-8 -*-
"""
h2
~~

A HTTP/2 implementation.
"""
__version__ = '4.1.0'
from __future__ import annotations

__version__ = "4.1.0"
72 changes: 39 additions & 33 deletions src/h2/config.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,32 @@
# -*- coding: utf-8 -*-
"""
h2/config
~~~~~~~~~

Objects for controlling the configuration of the HTTP/2 stack.
"""
from __future__ import annotations

import sys
from typing import Any


class _BooleanConfigOption:
"""
Descriptor for handling a boolean config option. This will block
attempts to set boolean config options to non-bools.
"""
def __init__(self, name):

def __init__(self, name: str) -> None:
self.name = name
self.attr_name = '_%s' % self.name
self.attr_name = f"_{self.name}"

def __get__(self, instance, owner):
return getattr(instance, self.attr_name)
def __get__(self, instance: Any, owner: Any) -> bool:
return getattr(instance, self.attr_name) # type: ignore

def __set__(self, instance, value):
def __set__(self, instance: Any, value: bool) -> None:
if not isinstance(value, bool):
raise ValueError("%s must be a bool" % self.name)
msg = f"{self.name} must be a bool"
raise ValueError(msg) # noqa: TRY004
setattr(instance, self.attr_name, value)


Expand All @@ -35,20 +38,19 @@ class DummyLogger:
conditionals being sprinkled throughout the h2 code for calls to
logging functions when no logger is passed into the corresponding object.
"""
def __init__(self, *vargs):

def __init__(self, *vargs) -> None: # type: ignore
pass

def debug(self, *vargs, **kwargs):
def debug(self, *vargs, **kwargs) -> None: # type: ignore
"""
No-op logging. Only level needed for now.
"""
pass

def trace(self, *vargs, **kwargs):
def trace(self, *vargs, **kwargs) -> None: # type: ignore
"""
No-op logging. Only level needed for now.
"""
pass


class OutputLogger:
Expand All @@ -61,15 +63,16 @@ class OutputLogger:
Defaults to ``sys.stderr``.
:param trace: Enables trace-level output. Defaults to ``False``.
"""
def __init__(self, file=None, trace_level=False):

def __init__(self, file=None, trace_level=False) -> None: # type: ignore
super().__init__()
self.file = file or sys.stderr
self.trace_level = trace_level

def debug(self, fmtstr, *args):
def debug(self, fmtstr, *args) -> None: # type: ignore
print(f"h2 (debug): {fmtstr % args}", file=self.file)

def trace(self, fmtstr, *args):
def trace(self, fmtstr, *args) -> None: # type: ignore
if self.trace_level:
print(f"h2 (trace): {fmtstr % args}", file=self.file)

Expand Down Expand Up @@ -147,32 +150,33 @@ class H2Configuration:

:type logger: ``logging.Logger``
"""
client_side = _BooleanConfigOption('client_side')

client_side = _BooleanConfigOption("client_side")
validate_outbound_headers = _BooleanConfigOption(
'validate_outbound_headers'
"validate_outbound_headers",
)
normalize_outbound_headers = _BooleanConfigOption(
'normalize_outbound_headers'
"normalize_outbound_headers",
)
split_outbound_cookies = _BooleanConfigOption(
'split_outbound_cookies'
"split_outbound_cookies",
)
validate_inbound_headers = _BooleanConfigOption(
'validate_inbound_headers'
"validate_inbound_headers",
)
normalize_inbound_headers = _BooleanConfigOption(
'normalize_inbound_headers'
"normalize_inbound_headers",
)

def __init__(self,
client_side=True,
header_encoding=None,
validate_outbound_headers=True,
normalize_outbound_headers=True,
split_outbound_cookies=False,
validate_inbound_headers=True,
normalize_inbound_headers=True,
logger=None):
client_side: bool = True,
header_encoding: bool | str | None = None,
validate_outbound_headers: bool = True,
normalize_outbound_headers: bool = True,
split_outbound_cookies: bool = False,
validate_inbound_headers: bool = True,
normalize_inbound_headers: bool = True,
logger: DummyLogger | OutputLogger | None = None) -> None:
self.client_side = client_side
self.header_encoding = header_encoding
self.validate_outbound_headers = validate_outbound_headers
Expand All @@ -183,7 +187,7 @@ def __init__(self,
self.logger = logger or DummyLogger(__name__)

@property
def header_encoding(self):
def header_encoding(self) -> bool | str | None:
"""
Controls whether the headers emitted by this object in events are
transparently decoded to ``unicode`` strings, and what encoding is used
Expand All @@ -195,12 +199,14 @@ def header_encoding(self):
return self._header_encoding

@header_encoding.setter
def header_encoding(self, value):
def header_encoding(self, value: bool | str | None) -> None:
"""
Enforces constraints on the value of header encoding.
"""
if not isinstance(value, (bool, str, type(None))):
raise ValueError("header_encoding must be bool, string, or None")
msg = "header_encoding must be bool, string, or None"
raise ValueError(msg) # noqa: TRY004
if value is True:
raise ValueError("header_encoding cannot be True")
msg = "header_encoding cannot be True"
raise ValueError(msg)
self._header_encoding = value
Loading
Loading