如何在Python中的自定义dict子类中添加类型注释?

时间:2019-12-20 15:26:23

标签: python

我有一个自定义的dict子类,它类似于defaultdict,但是将丢失的密钥传递给default_factory,因此它可以生成适当的值。

class KeyDefaultDict(dict):
    __slots__ = ("default_factory",)

    def __init__(self, default_factory, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.default_factory = default_factory

    def __missing__(self, key):
        if self.default_factory is None:
            raise KeyError(key)
        ret = self[key] = self.default_factory(key)
        return ret

    def __repr__(self):
        return (
            f"{type(self).__name__}({repr(self.default_factory)}, {super().__repr__()})"
        )


d = KeyDefaultDict(int)
print(d["1"] + d["2"] + d["3"])  # out: 6
print(d)  # out: KeyDefaultDict(<class 'int'>, {'1': 1, '2': 2, '3': 3})

我想像我的项目其余部分一样为此类添加类型注释,但是我找不到如何执行此操作的示例。 我看到typing模块使用外部类来添加注释。例如,defaultdict将被定义为typing.DefaultDict的{​​{1}}注释。

因此,这是一个外部类,它继承了class typing.DefaultDict(collections.defaultdict, MutableMapping[KT, VT])和泛型defaultdict。 但是,我认为他们可能是这样做的,因为他们不想更改原始的typing.MutableMapping。我发现了collections.defaultdictGeneric的子类的示例,但没有发现从Mapping之类的东西继承的类。

问题是:如何为此类添加类型注释以使其成为通用类? 我是否需要扩展其他内容或为注释创建外部类?

我正在使用python 3.7.5,我更喜欢直接从dict继承,因此出于性能原因,我不必实现必需的方法。

谢谢。

1 个答案:

答案 0 :(得分:2)

我来晚了,但是我只是在自己的代码库中完成了这项工作。

基本上,您需要使用键入Mapping generic 这是dict使用的通用名称,因此您可以定义其他类型,例如MyDict[str, int]

对于我的用例,我想要一个特殊的dict,它可以干净地格式化自身以进行日志记录,但是我会在整个过程中使用它 具有各种类型,因此需要输入支持。

方法:

import typing

# these are generic type vars to tell mapping to accept any type vars when creating a type
_KT = typing.TypeVar("_KT") #  key type
_VT = typing.TypeVar("_VT") #  value type


# `typing.Mapping` requires you to implement certain functions like __getitem__
# I didn't want to do that, so I just subclassed dict.
# Note: The type you're subclassing needs to come BEFORE 
# the `typing` subclass or the dict won't work.
# I had a test fail where my debugger showed that the dict had the items,
# but it wouldn't actually allow access to them

class MyDict(dict, typing.Mapping[_KT, _VT]):
    """My custom dict that logs a special way"""
    def __str__(self):
        # This function isn't necessary for your use-case, just including as example code
        return clean_string_helper_func(
            super(MyDict, self).__str__()
        )

# Now define the key, value typings of your subclassed dict
RequestDict = MyDict[str, typing.Tuple[str, str]]
ModelDict = MyDict[str, typing.Any]

现在使用自定义类型的子类字典:

from my_project.custom_typing import RequestDict #  Import your custom type

request = RequestDict()
request["test"] = ("sierra", "117")

print(request)

将输出为{ "test": ("sierra", "117") }