Reputation: 400
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.
Upvotes: 5
Views: 5726
Reputation:
On Python 3.9+ and Python 3.7+ if you do this
from __future__ import annotations
you can use list
as a type annotation. Your code should work as you've written it.
Upvotes: 0
Reputation: 963
As Devesh answered, your issue is that in effect you aren't typing the report_data
parameter with a list
of type ReportData
rather you are trying to get the element from list
at index ReportData
, and that is giving you the error as ReportData
is not a valid index.
When trying to type as a list
of type MyClass
you should use the typing.List
and pass that the element types.
Upvotes: 0
Reputation: 20490
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
Upvotes: 8