Course contentsShow
← Python
Lesson 573 of 1,0609. Type Safety and Code QualityFree lesson

Defining NewType for Static Identity Without Runtime Validation

Use NewType to distinguish otherwise compatible values during static type checking, recognizing that it returns the original value without runtime validation.

In this lesson, you will learn how to use NewType to create distinct identities for variables that share the same underlying data type, ensuring static type safety without the overhead of custom classes.

The Problem with Shared Types

Often, you might use primitive types like str or int to represent different things, such as user_id and product_id. While both are integers, passing a product_id into a function expecting a user_id could lead to catastrophic logic errors. Because they are both just int, standard type checkers like mypy won't flag this as an error.

Introducing NewType

The NewType helper from the typing module allows you to create a "distinct" type that is treated as a unique identity by static type checkers, while remaining completely transparent at runtime.

from typing import NewType

UserId = NewType('UserId', int)
ProductId = NewType('ProductId', int)

def get_user_name(user_id: UserId) -> str:
    return f"User_{user_id}"

uid = UserId(100)
pid = ProductId(200)

# This works fine
print(get_user_name(uid))

# This will trigger a static type error: 
# Argument 1 to "get_user_name" has incompatible type "ProductId"; expected "UserId"
print(get_user_name(pid))

How It Works

It is crucial to understand that NewType is a purely static construct. When your code runs, UserId(100) is literally just the integer 100. Python does not perform any runtime validation or create a wrapper object; it simply tells the type checker to treat UserId as a subtype of int.

If you attempt to perform arithmetic on your NewType, it will behave exactly like the base type. For example, uid + 5 results in an int, not a UserId. Because there is no runtime overhead, NewType is an incredibly efficient way to add an extra layer of semantic meaning to your code without impacting execution speed. Use it whenever you have values that are interchangeable in data structure, but conceptually distinct in your business logic.

Key Takeaway: NewType provides a lightweight way to enforce semantic identity in your code for static analysis, while remaining functionally identical to its base type during runtime execution.