Browse Chunks

Showing 5751-5800 of 7392 chunks

if isinstance(value, (str, bytes)):
CAT_9

This chunk tests whether a given value is an instance of str or bytes, allowing the program to branch based on data type. It addresses the pain point of inadvertently treating binary data as text (or vice versa), which can cause encoding errors or unexpected behavior. Developers reach for this check when processing input that may arrive as either Unicode strings or raw byte sequences, such as when reading from sockets, files, or user-provided data.

if isinstance(value, (str, bytes)):

class Container: def __init__(self, value: Optional[int] = None) -> None:
CAT_9

Defines a class initializer that sets an optional integer attribute to a provided value or None by default. Ensures instances start with a defined state, preventing attribute access errors from uninitialized fields. Used when creating a new data container that may or may not hold an integer value, such as a wrapper for nullable database fields.

class MyClass: def __init__(self, attr: DataType = default) -> None:

def greet(name: str) -> None:
CAT_9

This chunk defines a simple function that takes a string argument and returns nothing, typically used to print a greeting. It addresses the need to avoid duplicating greeting code across a program. Developers reach for this when they want to encapsulate a salutation routine for reuse.

def function_name(parameter_name: parameter_type) -> return_type:

def is_even(n: int) -> bool:
CAT_9

Defines a function named is_even that takes an integer n and returns a boolean indicating whether n is even.

def <function_name>(<param_name>: <param_type>) -> <return_type>:

def process(items: List[str]) -> Dict[str, int]:
CAT_9

This chunk defines a function that takes a list of strings and returns a dictionary counting occurrences of each string. It addresses the need to aggregate categorical data into a frequency map without writing manual loops. Developers reach for this pattern when they need to summarize string data for further analysis or reporting.

def function_name(seq: List[str]) -> Dict[str, int]:

def fetch_data(url: str) -> Optional[bytes]:
CAT_9

Function signature for fetching raw bytes from a URL, returning None on failure.

def <function_name>(<param>: <type>) -> <return_type>:

def calculate_average(values: Sequence[float]) -> float:
CAT_9

Defines a function signature for calculating the arithmetic mean of a sequence of floats, returning a float.

def <function_name>(<param_name>: Sequence[float]) -> float:

def merge_dicts(a: Mapping[str, Any], b: Mapping[str, Any]) -> Dict[str, Any]:
CAT_9

Combines two mappings into a new dictionary, with values from the second mapping overriding those from the first for duplicate keys.

def chunked(iterable: Iterable[T], size: int) -> Generator[List[T], None, None]:
CAT_9

def pipeline(*funcs: Callable[[Any], Any]) -> Callable[[Any], Any]:
CAT_9

Composes a sequence of unary callable objects into a single callable that applies them sequentially to an input value.

def pipeline(*funcs: Callable[[Any], Any]) -> Callable[[Any], Any]:

from typing import NewType
CAT_9

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

from typing import NewType

UserId = NewType('UserId', int)
CAT_9

Age = int
CAT_9

Assigns the int type to a variable, indicating it should hold integer values (used for type annotation or casting).

variable = type

def is_adult(age: Age) -> bool: return age >= 18
CAT_9

Defines a function that checks whether a given age is at least 18, returning a boolean result. This avoids duplicating the age >= 18 check throughout code, improving readability and maintainability. It is typically reached for when validating user eligibility for age-restricted content or actions.

def check_condition(value: int) -> bool: return value >= limit

from typing import List Vector = List[float]
CAT_9

A type alias for a list of floats representing a vector.

from typing import Dict, Any Json = Dict[str, Any]
CAT_9

Defines a type alias `Json` representing a dictionary with string keys and arbitrary values, commonly used for JSON‑compatible data structures in Python.

OrderId = NewType('OrderId', str)
CAT_9

Creates a distinct type alias for order identifiers, providing type safety without runtime overhead.

from typing import Literal Status = Literal['active', 'inactive'
CAT_9

from typing import Union, Optional
CAT_9

Imports Union and Optional type hints from the typing module for use in type annotations.

Payload = Union[Dict[str, Any], List[Any]]
CAT_9

A type alias representing a payload that can be either a dictionary mapping string keys to arbitrary values, or a list of arbitrary values.

Payload = Union[Dict[str, Any], List[Any]]

Validator = Callable[[Any], bool]
CAT_9

A type alias for a callable that takes any value and returns a boolean, typically used to represent validation functions.

Token = NewType('Token', bytes)
CAT_9

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

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

from typing import TypeVar, Generic
CAT_9

Imports TypeVar and Generic from the typing module to enable generic type definitions.

from typing import TypeVar, Generic

T = TypeVar('T')
CAT_9

Defines a generic type variable named T for use in Python's typing module to parameterize generic functions, classes, or protocols.

T = TypeVar('T')

class Container(Generic[T]):
CAT_9

Defines a generic class named Container parameterized by type variable T, indicating that the class can work with any type while retaining static type safety.

class Container(Generic[T]):

def get_first(items: list[T]) -> T: return items[0]
CAT_9

Returns the first element of a list.

def get_first(items: list[T]) -> T: return items[0]

U = TypeVar('U', bound=int)
CAT_9

V = TypeVar('V', covariant=True)
CAT_9

Defines a covariant type variable named V using typing.TypeVar, allowing it to be used in generic types where subtyping preserves subtype relationships.

V = TypeVar('V', covariant=True)

class Pair(Generic[T, U]):
CAT_9

Defines a generic class Pair with two type parameters T and U, representing a pair of two values.

def apply(func: Callable[[T], U], value: T) -> U: return func(value)
CAT_9

Applies a function to a value and returns the result.

from typing import Protocol
CAT_9

This import statement brings the Protocol class from the typing module into the current namespace. It allows developers to define structural interfaces that classes can implicitly satisfy by matching the required methods and attributes. This is useful when you want to enforce a contract without explicit inheritance.

from typing import Protocol

class Drawable(Protocol): def draw(self) -> None: pass
CAT_9

This chunk defines a structural interface (protocol) named Drawable that requires implementing a draw method returning None. It addresses the need for duck typing in statically typed Python code, allowing functions to accept any object with a draw method without requiring a common base class. It is triggered when designing flexible APIs where diverse renderable objects must be treated uniformly.

class protocol_name(Protocol): def method_name(self) -> return_type: pass

def render(obj: Drawable) -> None: obj.draw()
CAT_9

A function that renders a drawable object by invoking its draw method.

isinstance(obj, Drawable)
CAT_9

isinstance(obj, Drawable) returns True if obj is an instance of Drawable or a subclass thereof, or if obj provides the Drawable interface via virtual subclass registration. It prevents AttributeError when attempting to call Drawable-specific methods on objects that may not support them. Use it when you need to safely downcast or verify an object's capability before invoking Drawable-dependent operations.

isinstance(object, class_or_tuple)

TypeVar('T', bound=Drawable)
CAT_9

cast(Drawable, obj)
CAT_9

Asserts that obj is of type Drawable for static type checking, suppressing false-positive type errors.

def render_all(items: Iterable[Drawable]) -> None: for item in items: item.draw()
CAT_9

Iterates over an iterable of drawable objects and calls their draw method to render each item.

for item in items: item.draw()

def total_length(items: Iterable[SupportsLength]) -> int:\n return sum(len(item) for item in items)
CAT_9

This function calculates the total length of all items in an iterable by summing the length of each item. It addresses the pain point of writing verbose manual loops for length accumulation, which is error-prone and repetitive. It is triggered when you need to compute the combined size of a collection of length-supported objects, such as for input validation or buffer allocation.

def function_name(items: Iterable[SupportsLength]) -> int:\n return sum(len(item) for item in items)

def render_colored(obj: Drawable) -> None:\n obj.draw()\n print(f'Color: {obj.color}')
CAT_9

Renders a drawable object and prints its color attribute.

def render_colored(obj: Drawable) -> None:\n obj.draw()\n print(f'Color: {obj.color}')

from typing import Literal, Final
CAT_9

status: Literal['active', 'inactive'] = 'active'
CAT_9

MAX_SIZE: Final[int] = 1024
CAT_9

Defines a named constant that cannot be reassigned, providing type safety and clarity through explicit type annotation. This addresses the pain point of magic numbers and the risk of accidental modification of values that should remain fixed. It is used when a value must remain constant throughout the program's execution, particularly when the same value is used in multiple locations to ensure consistency and prevent unintended changes.

constant_name: Final[type] = value

x: int = 42
CAT_9

Declares a variable with an explicit type annotation and initializes it to a value. This makes the variable's intended type clear to both humans and static type checkers. It is used when a programmer wants to enforce type safety and improve code readability.

variable_name: type_ = default_value

name: str = 'Alice'
CAT_9

flag: bool = True
CAT_9

A boolean flag variable initialized to True, used as a toggle or flag to control program flow or state.

flag: bool = True

price: float = 19.99
CAT_9

Defines a variable named price with type float and default value 19.99.

<variable_name>: <type> = <literal>

count: int = len(items)
CAT_9

This chunk assigns the length of a collection to a variable with an explicit type annotation. It avoids repeated calls to len() and makes the intent clear for readers and static type checkers. Use when you need to reuse the length multiple times or want to add type information for clarity.

count: int = len(items)

message: str = 'Value: ' + str(value)
CAT_9

Constructs a labeled string representation of a value by concatenating the prefix 'Value: ' with the string conversion of the variable.

<variable>: str = '<prefix>' + str(<value>)

active: bool = not flag and count > 0
CAT_9

active is True when flag is False and count > 0

active: bool = not <flag> and <count> > 0

average: float = total / count if count else 0.0
CAT_9