【问题标题】:Function annotation for a list containing ABCMeta instances包含 ABCMeta 实例的列表的函数注释
【发布时间】:2017-08-25 22:53:30
【问题描述】:

我正在尝试使用 Python 函数注释 (PEP 3107) 作为 PyCharm 的类型提示,但没有这样做。问题可能与我使用ABCMeta有关:

import abc

class base(object, metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def test(self):
        pass

class deriv1(base):
    def test(self):
        return "deriv1"

class deriv2(base):
    def test(self):
        return "deriv2"

my_list = []
def append_to_list(el: base) -> list(base):
# def append_to_list(el):
#     """
#     :param el: item to add
#     :type: base
#     :return: items so far
#     :rtype: list[base]
#     """
   my_list.append(el)
   return my_list

append_to_list(deriv1())
a = append_to_list(deriv2())
for o in a:
    print(o.test())

此代码不运行。相反,我在def append_to_list 行上得到了TypeError: 'ABCMeta' object is not iterable

当我使用带有文档字符串类型提示的替代函数(上面代码中的注释行)时,一切正常。

这种类型提示可以使用注解吗?

【问题讨论】:

    标签: python annotations abstract-class


    【解决方案1】:

    它与 abc 无关,而是因为您告诉 Python 逐字评估

    list(base)
    

    这是不可能的,因为base 不可迭代。这就是错误消息告诉您的内容。

    你需要把它改成方括号并用引号括起来(因为list类型是不可下标的):

    def append_to_list(el: base) -> 'list[base]':
    

    或使用可下标的typing.List

    from typing import List
    
    def append_to_list(el: base) -> List[base]:
    

    表示它是一个包含base 对象的列表。

    【讨论】:

      猜你喜欢
      • 2014-09-11
      • 2015-11-19
      • 1970-01-01
      • 1970-01-01
      • 2015-04-05
      • 1970-01-01
      • 1970-01-01
      • 2010-10-15
      • 2014-11-12
      相关资源
      最近更新 更多