Python Forum
TypeError: 'type' object is not subscriptable - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: TypeError: 'type' object is not subscriptable (/thread-29335.html)



TypeError: 'type' object is not subscriptable - Stef - Aug-28-2020

Hi,

I'm fairly new to Python and I'm getting this error and to be honest, I have no clue why. I get it when running a pytest. The full stacktrace is:

Quote:emusim/pytest/test_central_bank.py:1: in <module>
from emusim.cockpit.supply.euro import CentralBank
emusim/cockpit/supply/__init__.py:1: in <module>
from .data_collector import DataCollector
emusim/cockpit/supply/data_collector.py:6: in <module>
class DataCollector(ABC):
emusim/cockpit/supply/data_collector.py:13: in DataCollector
def data_structure(self) -> OrderedDict[str, OrderedDict[str, bool]]:
E TypeError: 'type' object is not subscriptable

The relevant code is the following:

test_central_bank.py
from emusim.cockpit.supply.euro import CentralBank
__init__.py
from .data_collector import DataCollector
data_collector.py
from abc import ABC, abstractmethod
from collections import OrderedDict
from typing import List, KeysView


class DataCollector(ABC):

    def __init__(self):
        self.__data_dict: OrderedDict[str, OrderedDict[str, List[float]]] = OrderedDict()

    @abstractmethod
    @property
    def data_structure(self) -> OrderedDict[str, OrderedDict[str, bool]]:
        pass
What am I not seeing here?

Thanks in advance,
Stef


RE: TypeError: 'type' object is not subscriptable - Gribouillis - Aug-28-2020

Do you have to use typing? Why not simply write
from abc import ABC, abstractmethod, abstractproperty
from collections import OrderedDict
 
class DataCollector(ABC):
 
    def __init__(self):
        self.__data_dict = OrderedDict()

    @property
    @abstractmethod
    def data_structure(self):
        pass
    
class Spam(DataCollector):

    @DataCollector.data_structure.getter
    def data_structure(self):
        return "stru"

if __name__ ==  '__main__':
    s = Spam()
    print(s.data_structure)
If you really want to clutter the code with use typing, note that typing.OrderedDict is not the same as collections.OrderedDict. I guess you need to use the former in the type declarations.