def compute(x: int | float) -> float:
Type System & Annotations

Meaning

Defines a reusable function that accepts a numeric argument which can be an int or a float and guarantees a float result. Use it when you want a single, type‑annotated entry point that works with both integer and floating‑point inputs.

Primary Function

API design

Communicative Purpose

Creates a clear, statically‑annotated contract for a numeric computation.

Pattern

def function_name(param_name: param_type) -> return_type:

Core Structure

def (...) -> ...:

Função primária

API design

Propósito comunicativo

Creates a clear, statically‑annotated contract for a numeric computation.

Situações de gatilho

When implementing a calculation that may receive either int or float (e.g., user‑provided numeric input), when adding type hints to improve IDE support, when writing utility math helpers.

Contextos

General‑purpose Python codebases, data‑processing scripts, scientific computing modules, any project targeting Python 3.10+.

Padrão

def function_name(param_name: param_type) -> return_type:

Estrutura central

def (...) -> ...:

Slots de substituição

function_name: identifier, param_name: identifier, param_type: type expression (e.g., int | float), return_type: type expression (e.g., float)

Colocados típicos

  • type hints
  • annotations
  • return statement
  • docstring

Substituições comuns

  • Using Union[int
  • float] from typing
  • omitting the return annotation
  • using Any for broader flexibility

Erros comuns

Forgetting that | syntax requires Python 3.10+, confusing static type hints with runtime checks, returning an int when a float is expected

Similar / contraste

A plain def without annotations (no static type info), a function using overloads for separate int and float signatures

Interferências

Coming from Java: may expect method overloading instead of union types — Python uses union types for flexible parameter types.

Família do chunk

  • function definition
  • type hinting
  • union type
  • function signature

Nuance

Avoid using union types when a more specific protocol or abstract base class would better express intent; union types can hinder static analysis if overused; performance impact is negligible as unions are erased at runtime.

Efeito pragmático

Enables static type checkers to accept both integers and floats, reducing runtime type-checking boilerplate while maintaining clarity.

Dica de memória

Think of a function signature like a flexible adapter plug that accepts either a US or EU plug — both work, but the adapter knows how to handle each.

Nota

The int | float union syntax requires Python 3.10+ (PEP 604).

Upgrade path

Use overloads or a TypeVar bound to a numeric protocol for more precise typing

Frequência: Very highFormulaicidade: Semi-fixedTipo de construção: function_definition_with_type_hintsPrioridade de aquisição: Recognition firstPrioridade de output: BothTag de espaçamento: Immediate

Log in to save chunks.