Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a list of custom class as argument of function in Python 3.6

I want to type the inputs of a class method in Python 3. I want the argument to be a list of a custom class I created. The definition of the method is as follows:

def add_report_data(self, report_data: list[ReportData]):
    pass

ReportData is a regular class defined as follows:

class ReportData:
    def __init__(self, system: str, value: int):
        self.__system = system
        self.__value = value

When executing my code I receive the following error:

    def add_report_data(self, report_data: list[ReportData]):
TypeError: 'type' object is not subscriptable

However, changing the type of report_data to simply list is able to execute, but this is not exactly what I want to do. Any idea on what's going on? Thanks.

like image 256
Alejandro Villegas Avatar asked Jan 27 '23 04:01

Alejandro Villegas


1 Answers

You want to import typing.List and do List[ReportData]

List[ReportData] refers to the generic version of list used for typing instead of list[ReportData], which refers to the data type list

#Importing List from typing
from typing import List

class ReportData:
    def __init__(self, system: str, value: int):
        self.__system = system
        self.__value = value

class A:
    #Using List[ReportData]
    def add_report_data(self, report_data: List[ReportData]):
        pass
like image 68
Devesh Kumar Singh Avatar answered Jan 31 '23 23:01

Devesh Kumar Singh