Token = NewType('Token', bytes)
Type System & Annotations

Meaning

Defines a distinct type alias named Token based on bytes using typing.NewType for enhanced type safety.

Primary Function

Creates a new type that is distinct from plain bytes at static type-check time while retaining bytes at runtime.

Communicative Purpose

Signal that a value represents a token rather than generic bytes, preventing accidental mixing.

Pattern

NewType('<Name>', <base_type>)

Core Structure

NewType('Token', bytes)

Função primária

Creates a new type that is distinct from plain bytes at static type-check time while retaining bytes at runtime.

Propósito comunicativo

Signal that a value represents a token rather than generic bytes, preventing accidental mixing.

Situações de gatilho

When you need a token-like value (e.g., authentication token) that should not be confused with plain byte strings.

Contextos

Type annotations, function parameters, return types, variable declarations where a token is expected.

Padrão

NewType('<Name>', <base_type>)

Estrutura central

NewType('Token', bytes)

Slots de substituição

Token bytes

Colocados típicos

  • NewType typing bytes Token type

Substituições comuns

  • UserId = NewType('UserId'
  • int) Token = NewType('Token'
  • str)

Erros comuns

Confusing NewType with a simple alias (Token = bytes) Forgetting to import NewType from typing

Similar / contraste

Simple type alias: Token = bytes typing.NewType vs. typing.NewType

Interferências

Do not treat NewType as a runtime distinct type; it is only for static type checking.

Família do chunk

  • typing.NewType
  • type alias pattern

Nuance

At runtime, Token values are still bytes; the distinction exists only for static type checkers.

Efeito pragmático

Improves code clarity and prevents accidental misuse of byte values as tokens.

Dica de memória

Token = NewType('Token', bytes)

Upgrade path

Using NewType for other distinct types like UserId = NewType('UserId', int)

Tipo de construção: type alias using typing.NewTypeTag de espaçamento: Medium-term

Log in to save chunks.