Python type hints - specify key, value type for dict subclass

拥有回忆 提交于 2020-01-14 05:16:12

问题


Say I have

class A(dict): pass

Is there any way to specify the type of the key and values of A ? Can it be done in a way that the types are inherited - so class B(A) would inherit the type values for, say, key and would be able to override the type of value ?

Ideally this would be done via the type hints introduced in pep-0484 - but note I am on python 2 so I would need a solution with type comments. If however this is not possible a solution involving metaclasses or any other hack would be acceptable.


回答1:


All type interactions with your class go through methods, so annotate those methods. A.__setitem__(self, key, value): is called for setting a key-value pair and can be annotated to indicate the types expected.

Any valid PEP 484 annotation would do here, including type comments if you need Python 2 compatibility.

Those annotations would be inherited to B unless B overrides the methods.




回答2:


Elaborating on @MartijnPieters answer (I am using Pycharm 5.0.4 so behavior below may be due to the standard or to an IDE bug/feature)

_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

So one needs to override all methods (key value type info is local to the individual methods). IOW, unlike the case for parameters or attributes etc where one can do:

class A(object):

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

this is a NOOP:

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

Moreover there seems to be no way to be able to specify the types as class variables which could be readily overridden in subclasses.



来源:https://stackoverflow.com/questions/36811192/python-type-hints-specify-key-value-type-for-dict-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!