From c6cc3708f45c9e581a719852d4f1082528941701 Mon Sep 17 00:00:00 2001 From: Jean-Paul Calderone Date: Fri, 2 Dec 2022 08:38:46 -0500 Subject: [PATCH] Fixup the annotations a bit --- src/allmydata/testing/web.py | 2 +- src/allmydata/util/dictutil.py | 15 +++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/allmydata/testing/web.py b/src/allmydata/testing/web.py index 4af2603a8..72ecd7161 100644 --- a/src/allmydata/testing/web.py +++ b/src/allmydata/testing/web.py @@ -140,7 +140,7 @@ class _FakeTahoeUriHandler(Resource, object): isLeaf = True - data: BytesKeyDict[bytes, bytes] = attr.ib(default=attr.Factory(BytesKeyDict)) + data: BytesKeyDict[bytes] = attr.ib(default=attr.Factory(BytesKeyDict)) capability_generators = attr.ib(default=attr.Factory(dict)) def _generate_capability(self, kind): diff --git a/src/allmydata/util/dictutil.py b/src/allmydata/util/dictutil.py index 0a7df0a38..c436ab963 100644 --- a/src/allmydata/util/dictutil.py +++ b/src/allmydata/util/dictutil.py @@ -2,6 +2,10 @@ Tools to mess with dicts. """ +from __future__ import annotations + +from typing import TypeVar, Type + class DictOfSets(dict): def add(self, key, value): if key in self: @@ -64,7 +68,10 @@ class AuxValueDict(dict): self.auxilliary[key] = auxilliary -class _TypedKeyDict(dict): +K = TypeVar("K") +V = TypeVar("V") + +class _TypedKeyDict(dict[K, V]): """Dictionary that enforces key type. Doesn't override everything, but probably good enough to catch most @@ -73,7 +80,7 @@ class _TypedKeyDict(dict): Subclass and override KEY_TYPE. """ - KEY_TYPE = object + KEY_TYPE: Type[K] def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) @@ -98,13 +105,13 @@ for _method_name in ["__setitem__", "__getitem__", "setdefault", "get", del _method_name -class BytesKeyDict(_TypedKeyDict): +class BytesKeyDict(_TypedKeyDict[bytes, V]): """Keys should be bytes.""" KEY_TYPE = bytes -class UnicodeKeyDict(_TypedKeyDict): +class UnicodeKeyDict(_TypedKeyDict[str, V]): """Keys should be unicode strings.""" KEY_TYPE = str