【问题标题】:Is it possible to return a list with generic type in a function [duplicate]是否可以在函数中返回具有泛型类型的列表[重复]
【发布时间】:2021-09-08 03:58:41
【问题描述】:

有如下功能:

import pdfplumber
from pdfplumber.page import Page
def searchFromFile(path:str,keyword:str) -> list[Page]:
  with pdfplumber.open(path) as pdf:
    result = [Page]
    for page in pdf.pages:
        pageText = page.extract_text()
        if pageText != None and keyword in pageText:
            result.append(page)
    return result

为了更准确,我将返回的list定义为Java中的泛型类型,即list[Page],但它不起作用并出现错误:

TypeError: 'type' object is not subscriptable

问题:是否可以将返回的list 定义为泛型类型?

【问题讨论】:

  • 应该可以。你得到了什么错误?您是否已经定义了 Page 类?
  • @Barmar 我粘贴了整个函数,所以Page 来自pdfplumber
  • 您需要 Python 3.9 或更高版本才能使用 list 作为泛型类型。
  • 那就不要使用list[Page];使用typing.List[Page]

标签: python python-3.x generic-type-argument


【解决方案1】:

在 Python 3.9 之前,内置的 list 才成为泛型类型。在早期版本中,您必须改用 List(来自 typing 模块)。

from typing import List


def searchFromFile(path:str, keyword:str) -> List[Page]:

【讨论】:

  • 非常感谢,我试过了,它确实有效:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 2020-07-06
  • 2013-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多