Browse Chunks
Showing 5751-5800 of 7392 chunks
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)):
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:
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:
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>:
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]:
Function signature for fetching raw bytes from a URL, returning None on failure.
def <function_name>(<param>: <type>) -> <return_type>:
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:
Combines two mappings into a new dictionary, with values from the second mapping overriding those from the first for duplicate keys.
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]:
Creates a distinct nominal type for type hinting based on an existing type, providing nominal typing without runtime overhead.
from typing import NewType
Assigns the int type to a variable, indicating it should hold integer values (used for type annotation or casting).
variable = type
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
A type alias for a list of floats representing a vector.
Defines a type alias `Json` representing a dictionary with string keys and arbitrary values, commonly used for JSON‑compatible data structures in Python.
Creates a distinct type alias for order identifiers, providing type safety without runtime overhead.
Imports Union and Optional type hints from the typing module for use in type annotations.
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]]
A type alias for a callable that takes any value and returns a boolean, typically used to represent validation functions.
Defines a distinct type alias named Token based on bytes using typing.NewType for enhanced type safety.
NewType('<Name>', <base_type>)
Imports TypeVar and Generic from the typing module to enable generic type definitions.
from typing import TypeVar, Generic
Defines a generic type variable named T for use in Python's typing module to parameterize generic functions, classes, or protocols.
T = TypeVar('T')
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]):
Returns the first element of a list.
def get_first(items: list[T]) -> T: return items[0]
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)
Defines a generic class Pair with two type parameters T and U, representing a pair of two values.
Applies a function to a value and returns the result.
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
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
A function that renders a drawable object by invoking its draw method.
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)
Asserts that obj is of type Drawable for static type checking, suppressing false-positive type errors.
Iterates over an iterable of drawable objects and calls their draw method to render each item.
for item in items: item.draw()
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)
Renders a drawable object and prints its color attribute.
def render_colored(obj: Drawable) -> None:\n obj.draw()\n print(f'Color: {obj.color}')
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
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
A boolean flag variable initialized to True, used as a toggle or flag to control program flow or state.
flag: bool = True
Defines a variable named price with type float and default value 19.99.
<variable_name>: <type> = <literal>
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)
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 is True when flag is False and count > 0
active: bool = not <flag> and <count> > 0