gh-104050: Argument clinic: improve typing around adding C converters (#107209)

This commit is contained in:
Alex Waygood 2023-07-25 09:18:19 +01:00 committed by GitHub
parent 3b309319cc
commit dbfe73837d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 13 additions and 7 deletions

View File

@ -44,6 +44,7 @@ from typing import (
NoReturn, NoReturn,
Protocol, Protocol,
TypeGuard, TypeGuard,
TypeVar,
overload, overload,
) )
@ -2647,10 +2648,12 @@ class LandMine:
fail("Stepped on a land mine, trying to access attribute " + repr(name) + ":\n" + self.__message__) fail("Stepped on a land mine, trying to access attribute " + repr(name) + ":\n" + self.__message__)
CConverterClassT = TypeVar("CConverterClassT", bound=type["CConverter"])
def add_c_converter( def add_c_converter(
f: type[CConverter], f: CConverterClassT,
name: str | None = None name: str | None = None
) -> type[CConverter]: ) -> CConverterClassT:
if not name: if not name:
name = f.__name__ name = f.__name__
if not name.endswith('_converter'): if not name.endswith('_converter'):
@ -2659,7 +2662,7 @@ def add_c_converter(
converters[name] = f converters[name] = f
return f return f
def add_default_legacy_c_converter(cls): def add_default_legacy_c_converter(cls: CConverterClassT) -> CConverterClassT:
# automatically add converter for default format unit # automatically add converter for default format unit
# (but without stomping on the existing one if it's already # (but without stomping on the existing one if it's already
# set, in case you subclass) # set, in case you subclass)
@ -2670,16 +2673,19 @@ def add_default_legacy_c_converter(cls):
def add_legacy_c_converter( def add_legacy_c_converter(
format_unit: str, format_unit: str,
**kwargs **kwargs: Any
) -> Callable[[ConverterType], ConverterType]: ) -> Callable[[CConverterClassT], CConverterClassT]:
""" """
Adds a legacy converter. Adds a legacy converter.
""" """
def closure(f): def closure(f: CConverterClassT) -> CConverterClassT:
added_f: Callable[..., CConverter]
if not kwargs: if not kwargs:
added_f = f added_f = f
else: else:
added_f = functools.partial(f, **kwargs) # mypy's special-casing for functools.partial
# can't quite grapple with this code here
added_f = functools.partial(f, **kwargs) # type: ignore[arg-type]
if format_unit: if format_unit:
legacy_converters[format_unit] = added_f legacy_converters[format_unit] = added_f
return f return f