Union; Dict
Type System & Annotations

Meaning

A type annotation indicating that a value can be either a list of integers or a dictionary mapping strings to arbitrary types.

Primary Function

To specify that a variable, function parameter, or return value may accept either a list of integers or a dictionary with string keys and arbitrary values, enabling flexible yet statically typed interfaces.

Communicative Purpose

To communicate to type checkers and human readers that the accepted data can be one of two heterogeneous container types, allowing flexible input while preserving static type safety.

Pattern

Union[TypeA, TypeB] where TypeA and TypeB are themselves parameterized generic types

Core Structure

Union[TypeA, TypeB] (with TypeA and B as placeholders for any valid type expressions)

Função primária

To specify that a variable, function parameter, or return value may accept either a list of integers or a dictionary with string keys and arbitrary values, enabling flexible yet statically typed interfaces.

Propósito comunicativo

To communicate to type checkers and human readers that the accepted data can be one of two heterogeneous container types, allowing flexible input while preserving static type safety.

Situações de gatilho

When designing functions or APIs that need to accept either a homogeneous list of integer IDs or a mapping of string keys to values of any type, such as parsers that accept either a list of identifiers or a metadata dictionary.

Contextos

Found in function signatures, variable annotations, return type annotations, and variable declarations in Python code that uses the typing module, especially in data‑processing pipelines, configuration handlers, and API interfaces.

Padrão

Union[TypeA, TypeB] where TypeA and TypeB are themselves parameterized generic types

Estrutura central

Union[TypeA, TypeB] (with TypeA and B as placeholders for any valid type expressions)

Colocados típicos

  • Used with function definitions (def foo(x: Union[List[int]
  • Dict[str
  • Any]]) -> None:)
  • variable annotations
  • return annotations
  • and in conjunction with TypedDict
  • Protocol
  • or Any from the typing module.

Substituições comuns

  • - List[int] | Dict[str
  • Any] (Python 3.10+ union operator) – more concise
  • requires Python 3.10+. - List[int] | Dict[str
  • int] – more specific if values are known to be ints
  • increases safety but reduces flexibility. - Any – disables type checking
  • loses safety. - Union[List[int]
  • Dict[str
  • str]] – more specific value type
  • increases safety but less flexible. - Union[List[int]
  • Dict[str
  • Any]
  • None] – adds optional None to represent missing data.

Erros comuns

- Forgetting to import Union, List, Dict, Any from typing → NameError at runtime or type‑checker error. - Using bare list and dict literals like Union[list, dict] → loses parameterization, less precise typing. - Misspelling Union (e.g., union or Union) → NameError. - Omitting Any import → NameError when using Dict[str, Any]. - Misplacing brackets, e.g., Union[List[int], Dict[str, Any]] missing a closing bracket → SyntaxError.

Similar / contraste

- Optional[int] – represents Union[int, None] for optional scalar values. - Union[int, str] – union of scalar types, not container types. - Tuple[int, ...] – variable‑length tuple of ints, not a union of containers. - Dict[str, Any] – single dictionary type, not a union. - List[Union[int, str]] – list whose elements can be int or str, different nesting.

Interferências

- Coming from Java: may use Object or raw Object type instead of Union[List[int], Dict[str, Any]] → loses static type safety; use typing.Union or the pipe operator. - Coming from JavaScript: may assume any object can be used interchangeably → need explicit type annotations for static checking. - Coming from C: may use void* or void pointers → not type‑safe; prefer typing.Union with proper generics or Protocol. - Coming from TypeScript: may write number[] | Record<string, any> → similar syntax but must import typing.List and typing.Dict in Python. - Coming from C#: may use object or dynamic → bypasses type checking; prefer explicit Union or Protocol definitions.

Família do chunk

  • List[int]
  • Dict[str
  • Any]
  • Tuple[int
  • ...]
  • Set[str]
  • Union[int
  • str]
  • Optional[int]
  • Tuple[List[int]
  • Dict[str
  • Any]]

Nuance

(1) Avoid when the data is homogeneous (only list of ints or only dict) – the union adds unnecessary complexity and can hinder type inference. (2) No runtime performance impact; Union is a pure typing construct erased at runtime. (3) The Any inside Dict[str, Any] disables further type checking of values; if you later need to enforce a specific value type, replace Any with a concrete type or use TypedDict.

Efeito pragmático

Using this union type lets functions accept flexible input shapes while retaining static type safety, reducing runtime type‑checking bugs and improving IDE autocompletion and refactoring safety.

Dica de memória

Think of a Union type like a universal power outlet that can accept either a two‑prong plug (a list of ints) or a three‑prong plug (a dict with string keys) – the device works with either plug shape.

Nota

Union types are erased at runtime; isinstance checks must be performed against the concrete types (list or dict). The Any inside the dictionary means the type checker cannot infer anything about the dictionary’s values.

Upgrade path

Progress to more precise types such as TypedDict for the dictionary structure, NewType or custom classes for the list, or use Protocol to define expected behaviors instead of relying on Any.

Tipo de construção: Parameterized generic type union using typing.Union with parameterized generics (List[int] and Dict[str, Any])Tag de espaçamento: Medium-term

Log in to save chunks.