Browse Chunks

Showing 5801-5850 of 7392 chunks

total: int = sum(numbers)
CAT_9

Assigns the sum of numbers to a variable named total with type annotation int.

total: int = sum(numbers)

is_active: bool = user.is_logged_in and not user.is_banned
CAT_9

This chunk sets a boolean flag indicating whether a user is active by checking that they are logged in and not banned. It combines two boolean attributes with a logical AND and NOT to produce a clear activation condition. Developers reach for this pattern when they need to gate access to features based on user state.

flag: bool = account.is_logged_in and not account.is_banned

full_name: str = f'{first} {last}'
CAT_9

The variable full_name holds a string that concatenates the first and last name with a space.

f'{first} {last}'

scale: float = max_value / min_value if min_value != 0 else 1.0
CAT_9

Computes a safe scale factor as the ratio of max_value to min_value, defaulting to 1.0 when min_value is zero to avoid division by zero.

<variable>: float = <max> / <min> if <min> != 0 else 1.0

Set[float]
CAT_9

Type annotation indicating a set containing floating-point numbers.

Set[<type>]

Tuple[int, str, float]
CAT_9

Specifies a tuple containing exactly three elements: an integer, a string, and a floating‑point number. It provides static type information for heterogeneous tuples, helping catch mismatched element types early. Use it when a function returns or accepts a fixed‑size record with known types per position.

Use Tuple[int, str, float] as a type hint for a function returning a three‑element heterogeneous tuple.

List[List[float]]
CAT_9

Represents a two-dimensional list (matrix) of floating-point numbers.

List[List[float]]

Dict[str, Set[Tuple[int, float]]]
CAT_9

A type annotation representing a dictionary that maps string keys to sets of tuples, each tuple containing an integer and a float.

Dict[KeyType, Set[Tuple[IntType, FloatType]]] where KeyType=str, IntType=int, FloatType=float

List[Dict[str, List[int]]]
CAT_9

A list of dictionaries where each key is a string mapping to a list of integers.

List[Dict[str, List[int]]]

Tuple[Set[float], List[Dict[str, int]]]
CAT_9

This type annotation specifies a tuple containing a set of floats and a list of dictionaries mapping strings to integers. It allows static type checkers to validate complex nested data structures. Use it when functions need to accept or return such heterogeneous collections to ensure correctness and catch type-related bugs early.

Tuple[Set[numeric_type], List[Dict[key_type, value_type]]]

Set[Tuple[List[int], Dict[str, float]]]
CAT_9

A type annotation representing a set of tuples, where each tuple contains a list of integers and a dictionary mapping string keys to floating‑point values. It describes a collection of unique records, each record consisting of an ordered list of integer identifiers and a mapping of string‑to‑float attributes (e.g., feature weights).

Set[Tuple[List[int], Dict[str, float]]]

flag: Optional[bool] = None
CAT_9

This chunk declares a variable that can hold a boolean value or None, indicating an unset state. It addresses the pain point of needing to represent tri-state logic (true, false, undefined) without using magic numbers or strings. The condition that triggers reaching for it is when a variable's absence of value must be explicitly distinguished from false, such as in configuration flags or optional parameters.

flag: Optional[bool] = None

items: Union[List[int], Set[int]] = []
CAT_9

A variable named items that can hold either a list of integers or a set of integers, initialized to an empty list.

items: Union[List[int], Set[int]] = []

def process(value: Union[str, int, float]) -> Optional[str]:
CAT_9

f'{obj!r}'
CAT_7

datetime.now()
CAT_7

Returns the current local date and time. This is used when timestamping events, measuring durations, or scheduling tasks. Reach for this when you need to record the exact moment an event occurs or calculate time differences.

datetime.now()

date.today()
CAT_7

Returns a date object representing the current local date. Avoids having to manually compute today's date from time modules or dealing with timezone complexities. Used when you need the current date for logging, file naming, deadlines, or any date‑based logic.

date.today()

datetime.strptime('2024-01-15', '%Y-%m-%d')
CAT_7

Parses a date‑time string into a datetime.datetime object using a specified format string. It eliminates the need for manual string slicing and reduces errors when converting user‑input or log timestamps. You reach for it when you have a date string that matches a known pattern and need to perform date arithmetic or storage.

datetime.strptime(date_string, format_string)

datetime.now().strftime('%Y-%m-%d %H:%M:%S')
CAT_7

Produces a string representation of the current local date and time formatted as 'YYYY-MM-DD HH:MM:SS'.

datetime.fromisoformat('2024-01-15T10:30:00')
CAT_7

Converts an ISO 8601 formatted string into a naive datetime object (or timezone‑aware if the string includes offset). Avoids manual string slicing and reduces errors when parsing timestamps from logs, APIs, or configuration files. Used when receiving timestamp strings that conform to the ISO 8601 standard and a datetime object is needed for further processing.

datetime.fromisoformat(iso_string)

datetime.now(timezone.utc)
CAT_7

Returns the current UTC date and time as a timezone-aware datetime object.

timedelta(days=7, hours=3)
CAT_7

Creates a timedelta object representing a duration of 7 days and 3 hours.

timedelta(days=<int>, hours=<int>)

datetime.combine(date.today(), time(9, 0))
CAT_7

Creates a datetime object representing today's date at 9:00 AM.

list.append(item)
CAT_7

dict[key] = value
CAT_7

set.add(item)
CAT_7

collections.Counter(iterable)
CAT_7

Creates a Counter object that counts hashable objects in the given iterable.

collections.Counter(<iterable>)

defaultdict(list)
CAT_7

A defaultdict with list factory automatically creates an empty list for missing keys, enabling automatic accumulation of values per key without explicit existence checks.

defaultdict(<factory>)

deque(maxlen=n)
CAT_7

Creates a bounded deque with a maximum length n; when the deque is full, adding new elements automatically discards the oldest elements.

deque(maxlen=<n>)

heapq.nlargest(3, iterable)
CAT_7

Returns the n largest elements from an iterable as a list in descending order. Avoids sorting the entire iterable when only top elements are needed. Triggered when needing efficient extraction of maximum values from large datasets.

heapq.nlargest(n, iterable)

collections.ChainMap(dict1, dict2)
CAT_7

Creates a single, updatable view that chains multiple mappings so that lookups check the first mapping then subsequent ones, and updates affect the first mapping.

array.array('I', data)
CAT_7

The array.array() function creates a mutable array of homogeneous data types from the array module. It addresses the need for memory-efficient storage of numeric data compared to Python lists, especially when handling large datasets or binary data. This is triggered when processing numerical data requiring compact representation and fast access, such as in scientific computing or file I/O operations.

array.array(typecode, initializer)

s.split()
CAT_7

Splits a string into a list of substrings using whitespace as the delimiter.

s.split()

s.startswith('prefix')
CAT_7

Checks whether a string begins with a specified prefix string.

s.startswith('prefix')

s.endswith('suffix')
CAT_7

Checks whether a string ends with a given suffix. It addresses the need to validate file names, URLs, or other strings that must terminate with a specific pattern. Developers reach for it when they need to conditionally process items based on their ending, such as filtering files by extension.

string.endswith(suffix)

@lru_cache(maxsize=256) def fibonacci(n): return n if n<2 else fibonacci(n-1)+fibonacci(n-2)
CAT_6

The @lru_cache decorator wraps a function to store its results in a least-recently-used cache, so repeated calls with the same arguments return instantly without re-executing the function body. This avoids redundant computation in recursive or expensive pure functions, dramatically improving performance when the same inputs occur frequently. It is applied when a function is deterministic and its output depends only on its inputs, and when the cost of recomputation outweighs the memory overhead of caching.

@lru_cache(maxsize=limit) def func_name(num): return num if num<2 else func_name(num-1)+func_name(num-2)

@singleton class Logger: pass
CAT_6

A decorator that ensures a class has only one instance and provides a global point of access to it.

@singleton class <ClassName>: pass

@event_handler(event='click') def on_click(): pass
CAT_6

Defines a click event handler using the event_handler decorator.

@event_handler(event='<event_name>') def <handler_name>(): pass

@async_timeout(seconds=5) async def fetch_url(url): pass
CAT_6

@my_decorator class MyClass: pass
CAT_6

Applying a decorator to a class definition to modify or enhance the class.

@<decorator> class <ClassName>: pass

@register class Plugin: name = 'plugin'
CAT_6

@singleton class Service: def __init__(self): self.value = 0
CAT_6

A singleton class that ensures only one instance exists and initializes its value attribute to zero.

@singleton class {ClassName}: def __init__(self): self.{attr} = {value}

@log_calls class Calculator: def add(self, a, b): return a + b
CAT_6

This chunk defines a class method wrapped with a logging decorator that records each call. It addresses the need to trace function invocations without modifying the method's core logic. You reach for this when debugging or monitoring application behavior.

@decorator class MyClass: def method(self, x, y): return x + y

@dataclass class Person: name: str age: int
CAT_6

Defines a simple data class for a person with name and age.

@dataclass class {ClassName}: {field_name}: {type} ...

@functools.total_ordering class Score: def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value def __lt__(self, other): return self.value < other.value
CAT_6

Provides automatic generation of missing rich comparison methods (__le__, __gt__, __ge__, __ne__) when you define __eq__ and __lt__ using the @functools.total_ordering decorator. This reduces boilerplate and potential inconsistencies when implementing ordering for custom classes. It is used when you need instances of a class to be sortable or comparable (e.g., for use with sorted(), min(), max(), or as keys in dictionaries) and want to define ordering based on a single attribute or simple comparison.

@functools.total_ordering class MyClass: def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value def __lt__(self, other): return self.value < other.value

@enum.unique class Status(Enum): PENDING = 'pending' APPROVED = 'approved' REJECTED = 'rejected'
CAT_6

Defines an enumeration named Status with three string-valued members: PENDING, APPROVED, REJECTED.

@deprecated class Legacy: def legacy_func(self): pass
CAT_6

A Python class marked with the @deprecated decorator, indicating that the class is outdated and should be avoided in new code.

@deprecated class <ClassName>: def <method_name>(self): pass

@functools.wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs)
CAT_6

A decorator wrapper that preserves the original function's metadata (name, docstring, annotations) using functools.wraps.

@functools.wraps(func)\ndef wrapper(*args, **kwargs):\n return func(*args, **kwargs)

functools.wraps(original)(lambda *args, **kwargs: original(*args, **kwargs))
CAT_6

Creates a transparent wrapper that forwards all arguments to the original function while preserving its metadata via functools.wraps.

functools.wraps(original)(lambda *args, **kwargs: original(*args, **kwargs))

wrapper.__wrapped__ is func
CAT_6

The __wrapped__ attribute of a wrapper function created with functools.wraps refers to the original function that was wrapped.