본문 바로가기

Error and Solve

[오류 해결] TypeError: 'type' object is not subscriptable / Python version 3.10 이상으로 올리기

반응형

 

 

오류: TypeError: 'type' object is not subscriptable

 

    def create_app(config: type[Config] = Config) :
TypeError: 'type' object is not subscriptable

'type' object가 찾을 수 없다는 에러가 발생했다.  

 

 

 

 

 

 

해결: python 3.10으로 올리기

 

 

TypeError: 'type' object is not subscriptable는 파이썬에서 흔히 발생하는 에러 중 하나로, 클래스나 타입 객체 자체에 인덱싱([])을 시도했을 때 생깁니다.

원인

예를 들어:

a = list[int]

이건 Python 3.9 이상에서는 정상 작동하지만, 3.8 이하 버전에서는 list라는 타입 객체는 [] 연산을 지원하지 않기 때문에 에러가 납니다.

또 다른 흔한 경우:

from typing import List

def func(x: type[int]):
    pass

여기서 type[int]라고 쓰면 안 되고, 그냥 int나 List[int]처럼 써야 합니다. type은 메타클래스(즉 클래스 자체의 타입)이기 때문에 []를 붙일 수 없습니다.

해결 방법

파이썬 버전 확인

  • Python 3.9 이상: list[int], dict[str, int] 같은 새로운 타입힌트 문법 사용 가능.
  • Python 3.8 이하: 반드시 typing.List, typing.Dict 같은 구버전 스타일을 사용해야 합니다.
from typing import List, Dict

a: List[int] = [1, 2, 3]
b: Dict[str, int] = {"a": 1}

 

 

가장 쉬운 해결 방법은 python 버전을 3.10 이상으로 다시 만드는 것이다. 

 

 

conda 환경을 다시 깔았다. 

 

conda env remove -n old_env 

conda create -n new_env python=3.10

conda env remove -n old_env 

conda create -n new_env python=3.10

 

 

 

 

 

 

반응형