pythonpython-3.xgeneric-type-argument

Is it possible to return a list with generic type in a function


There is the following function:

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

In order to be more accurate, I defined the returned list with a generic type like in Java, i.e.list[Page], but it didn't work and got error:

TypeError: 'type' object is not subscriptable

Question: Is is possible at all to define the returned list with generic type?


Solution

  • The built-in list wasn't made a generic type until Python 3.9. In earlier versions, you'll have to use List (from the typing module) instead.

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