from typing import NewType
Type System & Annotations

Meaning

Creates a distinct nominal type for type hinting based on an existing type, providing nominal typing without runtime overhead.

Primary Function

Create a distinct nominal type for type hints, enabling stronger type checking while preserving runtime representation.

Communicative Purpose

Introduce a new nominal type for type annotations to improve type safety and code clarity.

Pattern

from typing import NewType

Core Structure

from typing import NewType

Função primária

Create a distinct nominal type for type hints, enabling stronger type checking while preserving runtime representation.

Propósito comunicativo

Introduce a new nominal type for type annotations to improve type safety and code clarity.

Situações de gatilho

When you need a distinct type alias that is treated as a separate type by type checkers (e.g., UserId = NewType('UserId', int)) to prevent mixing of similar raw types.

Contextos

Typically placed at the top of a module in the imports section, or within type stub files; used when defining domain‑specific types like IDs, identifiers, or specialized numeric types.

Padrão

from typing import NewType

Estrutura central

from typing import NewType

Slots de substituição

<name>, <base_type>

Colocados típicos

  • int
  • str
  • float
  • Any
  • List
  • Dict

Substituições comuns

  • typing.NewType

Erros comuns

Using NewType as a runtime type; confusing with typing.NewAlias; forgetting to call NewType as a callable.

Similar / contraste

typing.NewAlias, typing.TypeAlias, typing.Alias

Interferências

Confusing NewType with a simple alias (type Alias = int) which does not create a distinct type for type checkers.

Família do chunk

  • typing imports
  • type hints
  • NewType
  • TypeAlias

Nuance

NewType creates a distinct nominal type only for static type checkers; at runtime it returns a function that returns its argument with a custom __name__.

Efeito pragmático

Signals to type checkers and readers that the value is a specialized kind of the base type, preventing accidental mixing of similar IDs.

Dica de memória

Think of creating a distinct ID type to avoid mixing user IDs with order IDs.

Tipo de construção: import statementTag de espaçamento: Immediate

Log in to save chunks.