Python의 NewType
발행: (2026년 1월 3일 오후 04:47 GMT+9)
3 min read
원문: Dev.to
Source: Dev.to
Overview
NewType 은 별개의 타입을 만들 수 있게 해 주며, 정적 타입 검사기(예: mypy)에서는 별도 타입으로 취급하지만 런타임에서는 기본 타입의 별칭으로 동작합니다. Python 3.5.2부터 사용할 수 있습니다.
Key Characteristics
- 새로운 타입은 고유하며 기본 타입과 다릅니다.
- 비‑union(즉,
typing.Union이 아닌) 타입에서만 생성할 수 있습니다. - 결과 타입은 기본 타입의 서브타입‑유사 타입처럼 동작합니다.
- 일반 클래스로 서브클래싱 할 수 없습니다.
Syntax
from typing import NewType, reveal_type
# name: required string, must match the variable name
# tp: required non‑union type
NT1 = NewType('NT1', int)
NT2 = NewType('NT2', list[int | float])
Important notes
- 첫 번째 인수(
name)는 변수 이름과 동일해야 하는 문자열입니다. - 두 번째 인수(
tp)는 구체적인 비‑union 타입이어야 합니다. - union 타입(예:
int | float)을 사용하면 오류가 발생합니다.
Basic Usage
from typing import NewType, reveal_type
NT1 = NewType('NT1', int)
NT2 = NewType('NT2', list[int | float])
reveal_type(NT1(100)) # -> int (type checker shows test.NT1)
reveal_type(NT2([0, 1, 2])) # -> list (type checker shows test.NT2)
# The following are errors (type checker / runtime):
# NT3 = NewType('NT3', int | float) # ❌ Union not allowed
# NT50 = NewType('NT100', int) # ❌ Name mismatch
Interaction Between NewTypes
from typing import NewType
NT1 = NewType('NT1', int)
NT2 = NewType('NT2', NT1)
# Assignments
a1: NT1 = 100 # ❌ Error
a2: NT1 = NT1(100) # ✅ No error
a3: NT1 = NT2(100) # ❌ Error
a4: NT1 = NT2(NT1(100)) # ✅ No error
a5: NT1 = NT1(NT2(100)) # ❌ Error
b1: NT2 = 100 # ❌ Error
b2: NT2 = NT1(100) # ❌ Error
b3: NT2 = NT2(100) # ❌ Error
b4: NT2 = NT2(NT1(100)) # ✅ No error
b5: NT2 = NT1(NT2(100)) # ❌ Error
c1: int = 100 # ✅ No error
c2: int = NT1(100) # ✅ No error
c3: int = NT2(100) # ❌ Error
c4: int = NT2(NT1(100)) # ✅ No error
c5: int = NT1(NT2(100)) # ❌ Error
print(a4 + b4 + c4) # ✅ No error
NewType with Type Aliases and Generics
from typing import NewType
type TA1 = int
type TA2[T] = T
NT1 = NewType('NT1', TA1) # ✅ No error
NT2 = NewType('NT2', TA2[int]) # ✅ No error
Invalid Generic Usage
from typing import NewType
NT = NewType('NT', list)
v: NT[int] # ❌ Error – NewType does not support generic parameters
Subclassing NewType
from typing import NewType
NT = NewType('NT', int)
class Cls(NT): # ❌ Error – NewType cannot be subclassed
pass
References
- Python documentation: typing.NewType
- Related memo: Memo for type‑hints‑related posts in Python
This article builds on earlier posts about type hints:
- Type hints in Python (part 1) (explains basic type hints)