본문 바로가기

Language

[Python 3.8] TypeError: 'type' object is not subscriptable

728x90

문제점

Python 3.8을 사용중인데 typing을 활용하여 타입에 대한 힌트를 지정할 때 다음과 같은 오류가 발생합니다.

Traceback (most recent call last):                                                                                                                                                  
  File "main.py", line 13, in <module>                                                                                                                                              
    def test(num_list: list[int]) -> list[int]:                                                                                                                    
TypeError: 'type' object is not subscriptable

원인

typing 힌트에서 제너릭에 대한 지원은 Python 3.9부터 시작됩니다.

관련 문서는 PEP 585 (https://peps.python.org/pep-0585/) 에 있습니다.

해결방법 1

Python에 대한 버전업이 가능하다면 3.9 이상으로 올리면 됩니다.

해결방법 2

Python에 대한 버전업이 불가능하다면 내장형 타입에 대한 Alias를 활용하면 됩니다.

일반적으로 이름은 동일하되 대문자로 시작합니다.

from typing import List

def test(num_list: List[int]) -> List[int]:
	pass
반응형