Python类型提示 - 为dict子类指定键,值类型

时间:2016-04-23 13:02:00

标签: python python-2.7 type-hinting

说我有

class A(dict): pass

有没有办法指定键的类型和A的值?是否可以以继承类型的方式完成 - 所以class B(A)会继承类型值,比如key,并且能够覆盖值的类型吗?

理想情况下,这可以通过pep-0484中引入的类型提示来完成 - 但请注意我在python 2上,所以我需要一个带有类型注释的解决方案。但是,如果不可能,则可以接受涉及元类或任何其他黑客的解决方案。

2 个答案:

答案 0 :(得分:2)

与您的类的所有类型交互都经过方法,因此请注释这些方法。调用A.__setitem__(self, key, value):来设置键值对,可以注释以指示预期的类型。

这里有任何有效的PEP 484注释,包括类型注释,如果你需要Python 2兼容性。

除非B覆盖方法,否则这些注释将继承到B

答案 1 :(得分:0)

阐述@MartijnPieters answer(我正在使用Pycharm 5.0.4,因此下面的行为可能是由于标准或IDE错误/功能)

_key_type_global = unicode

class A(dict):

    _key_type = unicode

    def __setitem__(self, key, value):
        """A._key_type is not recognised, _key_type_global is
        :type key: _key_type_global
        :type value: int
        """
        super(A, self).__setitem__(key, value)

class B(A): pass


a = A()
a['str'] = 'uy' # expected type unicode got str instead
a[u'str'] = 'uy' # no warn (?)
a[u'str'] = 1 # no warn

val = a[u'str'] # Pycharm does not give any type info on value so I have to 
# define __getitem__ too

# type info is inherited
b = B()
b['str'] = 'uy' # expected type unicode got str instead
b[u'str'] = 'uy' # no warn (?)
b[u'str'] = 1 # no warn

因此需要覆盖所有方法(键值类型信息是各个方法的本地方法)。 IOW,与参数或属性等的情况不同,人们可以这样做:

class A(object):

    def __init__(self, dct):
        self.dct = dct # type : dict[unicode, int]

这是一个NOOP:

class A(dict): # type dict[unicode, int]

此外,似乎无法将类型指定为可在子类中轻易覆盖的类变量。

相关问题