anchor
stringlengths
13
118
positive
stringclasses
235 values
Python code showing Structural pattern matching classes (v5)
from dataclasses import dataclass @dataclass class Point: x: int y: int def describe(point): match point: case Point(x=0, y=0): return 'Origin' case Point(x=0, y=y): return f'Y-axis at {y}' case Point(x=x, y=0): return f'X-axis at {x}' ca...
Tutorial on Can you show type hint that allows none python exa Python (v3)
from typing import Union def to_int(val: Union[str, float, int]) -> int: """Convert string, float or int to int.""" return int(val)
Python code showing Write code for readable tuple python. (v9)
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(3, 4) print(p.x, p.y) # access by name
Python snippet for weakvaluedictionary python. complete example
import weakref class Node: def __init__(self, val): self.val = val self.parent = None # strong reference would cause cycle parent = Node(1) child = Node(2) child.parent = weakref.ref(parent) # weak reference # Access: child.parent() returns None if parent was GC'd
Explain code to generate pseudo random numbers and sample in Python (v9)
import random def lottery(candidates, k=3): random.seed(42) chosen = random.sample(candidates, k) random.shuffle(candidates) return chosen
How make HTTP request is implemented in Python (v9)
import requests response = requests.get( 'https://api.example.com/data', headers={'Authorization': 'Bearer token'}, timeout=10 ) response.raise_for_status() data = response.json()
Practical use of Bottom up DP tutorial in Python (v2)
def fib_dp(n): """Fibonacci via bottom-up dynamic programming.""" if n < 2: return n dp = [0] * (n + 1) dp[1] = 1 for i in range(2, n + 1): dp[i] = dp[i-1] + dp[i-2] return dp[n]
Python code showing Show me how to file system operations pathlib pyth (v4)
from pathlib import Path base = Path.home() / 'projects' / 'myapp' base.mkdir(parents=True, exist_ok=True) # List all .py files recursively py_files = list(base.rglob('*.py')) # Read / write (base / 'config.txt').write_text('setting=value')
Tutorial on combination without repetition Python (v6)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
Python example of Best practice to wait for thread signals using thr (v5)
import threading event = threading.Event() def worker(): print("Waiting for start signal...") event.wait() print("Signal received, working!") t = threading.Thread(target=worker) t.start() event.set()
Common use case of Concurrent async tasks Python (v10)
import asyncio async def main(): """Run tasks concurrently with asyncio.gather.""" results = await asyncio.gather( fetch('http://api1.com'), fetch('http://api2.com'), fetch('http://api3.com'), ) return results
Practical use of : call parent class method in Python (v9)
class Animal: def __init__(self, name): self.name = name def speak(self): return f'{self.name} makes a sound' class Dog(Animal): def __init__(self, name, breed): super().__init__(name) self.breed = breed def speak(self): return super().speak() + ' - Woof!'
What is I want to understand how to chain multiple iterabl in Python? (v2)
import itertools def chain_all(*iterables): """Chain multiple iterables into one using itertools.""" return list(itertools.chain(*iterables)) # Usage: chain_all([1,2], [3,4], [5]) -> [1,2,3,4,5]
Beginner guide to Show me how to choose r items from list python in Python
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
How does Create pandas DataFrame tutorial work? (v3)
import pandas as pd df = pd.read_csv('data.csv') # Filter high_salary = df[df['salary'] > 100_000] # Group avg_by_dept = df.groupby('department')['salary'].mean() # New column df['bonus'] = df['salary'] * 0.10
Code for I want to understand choose r items from list pyth in Python (v7)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
Python code showing Write code for python higher order function decor (v9)
from functools import wraps def my_decorator(func): """Simple decorator that prints before and after.""" @wraps(func) def wrapper(*args, **kwargs): print('Before call') result = func(*args, **kwargs) print('After call') return result return wrapper
What is String manipulation tutorial in Python? (v10)
s = ' Hello, World! ' print(s.strip()) # remove whitespace print(s.lower()) # to lowercase print(s.upper()) # to uppercase print(s.replace('World', 'Python')) words = s.strip().split(', ') print('|'.join(words))
Python 3 What does structural pattern matching python 3.10 example code (v3)
def http_status(status): match status: case 200: return 'OK' case 404: return 'Not Found' case 500 | 503: return 'Server Error' case _: return 'Unknown'
Give me an example of python star unpacking example.
first, *middle, last = [1, 2, 3, 4, 5] print(first, last) # 1 5 print(middle) # [2, 3, 4] # Merge dicts Python 3.9+ a = {'x': 1} b = {'y': 2} c = {**a, **b} # {'x': 1, 'y': 2}
Python 3 Demonstrate python dict comprehension example in example code (v7)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
Restrict attributes with __slots__ tutorial Python guide (v9)
class Point: __slots__ = ('x', 'y') # restrict to only x, y def __init__(self, x, y): self.x = x self.y = y # No __dict__ => saves memory for millions of instances
Write a function to demonstrate How do I concatenate iterables without copying (v8)
import itertools def chain_all(*iterables): """Chain multiple iterables into one using itertools.""" return list(itertools.chain(*iterables)) # Usage: chain_all([1,2], [3,4], [5]) -> [1,2,3,4,5]
How Encapsulate state with closure is implemented in Python (v2)
def make_counter(start=0): """Closure that maintains a counter.""" count = [start] def increment(by=1): count[0] += by return count[0] return increment
How What is the best way to min heap python is implemented in Python (v6)
import heapq nums = [5, 1, 8, 3, 9, 2] heapq.heapify(nums) # in-place min-heap smallest = heapq.heappop(nums) nlargest = heapq.nlargest(3, nums)
Explain how to use := in python with code.
# Walrus operator: assign and use in same expression data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] filtered = [y for x in data if (y := x**2) > 25]
Python code showing Explain itertools.chain example python with code. (v7)
import itertools def chain_all(*iterables): """Chain multiple iterables into one using itertools.""" return list(itertools.chain(*iterables)) # Usage: chain_all([1,2], [3,4], [5]) -> [1,2,3,4,5]
How do I python walrus operator example?
# Walrus operator: assign and use in same expression data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] filtered = [y for x in data if (y := x**2) > 25]
Python code showing Explain flatten 2d list python one liner with code (v7)
matrix = [[1,2,3],[4,5,6],[7,8,9]] flat = [elem for row in matrix for elem in row]
Beginner guide to How do I unittest.mock patch python Python (v6)
from unittest.mock import patch, MagicMock def get_user(user_id): import requests return requests.get(f'/users/{user_id}').json() def test_get_user(): with patch('requests.get') as mock_get: mock_get.return_value.json.return_value = {'id': 1, 'name': 'Alice'} result = get_user(1) a...
Can you show avoid circular reference python examp with Python 3 (v3)
import weakref class Node: def __init__(self, val): self.val = val self.parent = None # strong reference would cause cycle parent = Node(1) child = Node(2) child.parent = weakref.ref(parent) # weak reference # Access: child.parent() returns None if parent was GC'd
Advanced : Unpack list into variables Python example (v9)
first, *middle, last = [1, 2, 3, 4, 5] print(first, last) # 1 5 print(middle) # [2, 3, 4] # Merge dicts Python 3.9+ a = {'x': 1} b = {'y': 2} c = {**a, **b} # {'x': 1, 'y': 2}
Python code to find key with maximum value in dictionary
scores = {'math': 88, 'physics': 95, 'chemistry': 91} top_subject = max(scores, key=scores.get)
Practical use of Code example: __eq__ and __hash__ python example in Python (v3)
class Point: def __init__(self, x, y): self.x, self.y = x, y def __eq__(self, other): return isinstance(other, Point) and self.x == other.x and self.y == other.y def __hash__(self): return hash((self.x, self.y))
Beginner guide to Give me an example of delegating generator python. Python (v2)
def flatten(nested): """Flatten nested iterables using yield from.""" for item in nested: if hasattr(item, '__iter__') and not isinstance(item, str): yield from flatten(item) else: yield item
Python example of What does timeit python look like in (v5)
import cProfile, pstats, timeit # Quick benchmark elapsed = timeit.timeit('sum(range(1000))', number=10_000) print(f'10k runs: {elapsed:.3f}s') # Full profiling cProfile.run('my_function()', 'output.prof') p = pstats.Stats('output.prof').sort_stats('cumulative') p.print_stats(10)
How Explain pattern matching python with code. is implemented in Python (v8)
def http_status(status): match status: case 200: return 'OK' case 404: return 'Not Found' case 500 | 503: return 'Server Error' case _: return 'Unknown'
Tutorial on Explain log to file and console python with code. Python (v7)
import logging from logging.handlers import RotatingFileHandler logger = logging.getLogger('myapp') logger.setLevel(logging.DEBUG) fh = RotatingFileHandler('app.log', maxBytes=1_000_000, backupCount=3) fh.setLevel(logging.INFO) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) logger.addHandler(fh) logger.add...
I want to understand how to chain generators using yield from.
def flatten(nested): """Flatten nested iterables using yield from.""" for item in nested: if hasattr(item, '__iter__') and not isinstance(item, str): yield from flatten(item) else: yield item
Write a function to demonstrate Show me how to python statistics module in . (v2)
import statistics as stats data = [2, 4, 4, 4, 5, 5, 7, 9] print(stats.mean(data)) # 5.0 print(stats.median(data)) # 4.5 print(stats.mode(data)) # 4 print(stats.stdev(data)) # 2.0
Common use case of What does structural subtyping python look like in Python (v2)
from typing import Protocol class Drawable(Protocol): def draw(self) -> None: ... def render(obj: Drawable) -> None: obj.draw() # Any class with draw() satisfies Drawable without inheritance
Understanding How do I wait for thread signals using threading.E in Python (v10)
import threading event = threading.Event() def worker(): print("Waiting for start signal...") event.wait() print("Signal received, working!") t = threading.Thread(target=worker) t.start() event.set()
Beginner guide to Show me how to python metaclass example in . Python (v8)
class SingletonMeta(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super().__call__(*args, **kwargs) return cls._instances[cls] class Config(metaclass=SingletonMeta): def __init__(self): self.debug = False
How Give me an example of basemodel pydantic python. is implemented in Python (v2)
from pydantic import BaseModel, Field, validator from typing import Optional class User(BaseModel): name: str email: str age: int = Field(gt=0, le=150) bio: Optional[str] = None @validator('email') def email_must_have_at(cls, v): if '@' not in v: raise ValueError('invalid e...
Demonstrate python gather coroutines result in Python 3.
import asyncio async def main(): """Run tasks concurrently with asyncio.gather.""" results = await asyncio.gather( fetch('http://api1.com'), fetch('http://api2.com'), fetch('http://api3.com'), ) return results
Python example of Ignore specific exception (v5)
from contextlib import suppress with suppress(FileNotFoundError): os.remove('nonexistent.txt') # no error raised
Python snippet: Can you show asynchronous function python example (v10)
import asyncio async def fetch_data(url: str) -> str: """Simulate async HTTP fetch.""" await asyncio.sleep(1) # simulate network delay return f'Data from {url}'
Python code showing Can you show word frequency python example (v5)
from collections import Counter words = 'the quick brown fox jumps over the lazy dog'.split() counts = Counter(words) print(counts.most_common(3))
Tutorial on snippet for filter rows pandas python. Python (v4)
import pandas as pd df = pd.read_csv('data.csv') # Filter high_salary = df[df['salary'] > 100_000] # Group avg_by_dept = df.groupby('department')['salary'].mean() # New column df['bonus'] = df['salary'] * 0.10
Common use case of snippet for run multiple coroutines concurrently p Python (v5)
import asyncio async def main(): """Run tasks concurrently with asyncio.gather.""" results = await asyncio.gather( fetch('http://api1.com'), fetch('http://api2.com'), fetch('http://api3.com'), ) return results
Python 3 Write code for make attribute read only python. example code (v10)
class Temperature: """Temperature class with Celsius/Fahrenheit via @property.""" def __init__(self, celsius=0): self._celsius = celsius @property def celsius(self): return self._celsius @celsius.setter def celsius(self, value): if value < -273.15: raise Val...
Write a function to demonstrate Can you show how to get all combinations python ex (v6)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
Understanding Show me how to python combination without repetiti in Python (v3)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
Tutorial on Singleton design pattern example tutorial Python
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance
How does snippet for load json file python. work? (v6)
import json # Deserialize with open('data.json') as f: data = json.load(f) # Serialize with open('output.json', 'w') as f: json.dump(data, f, indent=2) # String operations text = json.dumps({'key': 'value'}) obj = json.loads(text)
Python example of Freeze or pre-bind function arguments using functo
from functools import partial def send_email(to, subject, body, sender='noreply@example.com'): print(f"From: {sender} To: {to} Subject: {subject}") send_alert = partial(send_email, subject="SYSTEM ALERT")
Give me an example of python gather coroutines res with Python 3 (v10)
import asyncio async def main(): """Run tasks concurrently with asyncio.gather.""" results = await asyncio.gather( fetch('http://api1.com'), fetch('http://api2.com'), fetch('http://api3.com'), ) return results
Code for Explain write csv python with code. in Python (v3)
import csv # Read with headers as dicts with open('data.csv', newline='') as f: reader = csv.DictReader(f) rows = list(reader) # Write with open('out.csv', 'w', newline='') as f: writer = csv.DictWriter(f, fieldnames=['name', 'age']) writer.writeheader() writer.writerows(rows)
Write a function to demonstrate Can you show structural pattern matching python 3. (v3)
def http_status(status): match status: case 200: return 'OK' case 404: return 'Not Found' case 500 | 503: return 'Server Error' case _: return 'Unknown'
When to use I want to understand named expression python walru Python (v9)
# Walrus operator: assign and use in same expression data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] filtered = [y for x in data if (y := x**2) > 25]
Python code showing Give me an example of simple context manager using (v10)
from contextlib import contextmanager @contextmanager def timer(label=''): """Context manager that times a block.""" import time start = time.perf_counter() try: yield finally: elapsed = time.perf_counter() - start print(f'{label}: {elapsed:.4f}s')
Code for I want to understand min heap python. in Python (v3)
import heapq nums = [5, 1, 8, 3, 9, 2] heapq.heapify(nums) # in-place min-heap smallest = heapq.heappop(nums) nlargest = heapq.nlargest(3, nums)
Python I want to understand how to use queue in asyncio p complete example
import asyncio async def producer(queue): for i in range(5): await queue.put(i) await asyncio.sleep(0.1) async def consumer(queue): while True: item = await queue.get() print(f'Consumed {item}') queue.task_done() async def main(): q = asyncio.Queue() await asyn...
Python snippet: Code example: cache expensive function calls pytho (v4)
from functools import lru_cache @lru_cache(maxsize=None) def fibonacci(n): """Compute nth Fibonacci number using memoization.""" if n < 2: return n return fibonacci(n-1) + fibonacci(n-2)
Common use case of Demonstrate python map filter reduce example in 3 Python (v9)
from functools import reduce nums = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, nums)) evens = list(filter(lambda x: x % 2 == 0, nums)) total = reduce(lambda a, b: a + b, nums)
What is use Literal type to restrict parameter to set of e in Python? (v9)
from typing import Literal def set_mode(mode: Literal['read', 'write', 'append']): print(f"Opening in {mode} mode")
Python example of Give me an example of basemodel pydantic python. (v5)
from pydantic import BaseModel, Field, validator from typing import Optional class User(BaseModel): name: str email: str age: int = Field(gt=0, le=150) bio: Optional[str] = None @validator('email') def email_must_have_at(cls, v): if '@' not in v: raise ValueError('invalid e...
Python code showing Demonstrate __add__ python example in 3.
class Vector: def __init__(self, x, y): self.x, self.y = x, y def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __repr__(self): return f'Vector({self.x}, {self.y})'
What is Show me how to inject error into python generator in Python? (v10)
def safe_gen(): """Generator that handles injected exceptions.""" try: while True: yield except ValueError as e: print(f'Caught: {e}') yield 'recovered'
Python 3 : Process large file example code (v9)
# Memory-efficient line-by-line reading with open('large_file.txt', encoding='utf-8') as f: for line in f: process(line.rstrip('\n'))
Write a function to demonstrate Show me how to process large file python in . (v5)
# Memory-efficient line-by-line reading with open('large_file.txt', encoding='utf-8') as f: for line in f: process(line.rstrip('\n'))
Write a function to demonstrate Write code for how to make python class iterable (v5)
class MyList: def __init__(self, data): self._data = list(data) def __len__(self): return len(self._data) def __getitem__(self, index): return self._data[index]
How does Write code for python lazy slicing of infinite se work? (v2)
import itertools def take(n, iterable): """Return first n items of an iterable as a list.""" return list(itertools.islice(iterable, n))
Python I want to understand python nested function variab complete example (v6)
def make_adder(n): """Use nonlocal to modify enclosing scope variable.""" total = 0 def add(x): nonlocal total total += x + n return total return add
Python snippet: Write code for clone list python. (v7)
import copy original = [[1, 2, 3], [4, 5, 6]] shallow = copy.copy(original) # nested lists still shared deep = copy.deepcopy(original) # fully independent copy deep[0][0] = 99 print(original[0][0]) # still 1
What is Explain and show code to detect cycle in directed in Python? (v2)
def has_cycle(graph): visited = {} # 0: visiting, 1: visited def dfs(node): visited[node] = 0 for nxt in graph.get(node, []): if visited.get(nxt) == 0: return True if nxt not in visited and dfs(nxt): return True visited[node] = 1 return False return a...
When to use I want to understand what is yield keyword in pyth Python (v4)
def count_up(n): """Generator that yields numbers 0 to n-1.""" for i in range(n): yield i
Understanding I want to understand filter list with comprehensio in Python (v10)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
Practical use of generator.send() tutorial in Python (v7)
def accumulator(): """Generator that receives values via send() and accumulates.""" total = 0 while True: value = yield total if value is None: break total += value
Python snippet: mock in tests (v10)
from unittest.mock import patch, MagicMock def get_user(user_id): import requests return requests.get(f'/users/{user_id}').json() def test_get_user(): with patch('requests.get') as mock_get: mock_get.return_value.json.return_value = {'id': 1, 'name': 'Alice'} result = get_user(1) a...
Practical use of Explain weakvaluedictionary python with code. in Python (v9)
import weakref class Node: def __init__(self, val): self.val = val self.parent = None # strong reference would cause cycle parent = Node(1) child = Node(2) child.parent = weakref.ref(parent) # weak reference # Access: child.parent() returns None if parent was GC'd
Practical use of Write code for read file line by line python. in Python (v8)
# Memory-efficient line-by-line reading with open('large_file.txt', encoding='utf-8') as f: for line in f: process(line.rstrip('\n'))
Write a function to demonstrate Write code for python namedtuple example. (v5)
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(3, 4) print(p.x, p.y) # access by name
Python code showing Show me how to how to get all combinations python (v4)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
When to use Demonstrate singleton design pattern python exampl Python (v10)
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance
Common use case of How do I how to use nonlocal in python Python (v4)
def make_adder(n): """Use nonlocal to modify enclosing scope variable.""" total = 0 def add(x): nonlocal total total += x + n return total return add
Python 3 Convert int to bytes struct tutorial example code (v6)
import struct # Pack integers into bytes packed = struct.pack('>IHH', 2024, 3, 15) # big-endian uint32, uint16, uint16 print(packed) # Unpack yr, mo, dy = struct.unpack('>IHH', packed) print(yr, mo, dy)
Tutorial on I want to understand producer consumer asyncio pyt Python (v4)
import asyncio async def producer(queue): for i in range(5): await queue.put(i) await asyncio.sleep(0.1) async def consumer(queue): while True: item = await queue.get() print(f'Consumed {item}') queue.task_done() async def main(): q = asyncio.Queue() await asyn...
Tutorial on snippet for how to make class iterable python. Python
class Countdown: def __init__(self, start): self.start = start def __iter__(self): self.current = self.start return self def __next__(self): if self.current <= 0: raise StopIteration self.current -= 1 return self.current + 1
How does implement comparison operators __lt__ __gt__ __le_ work? (v3)
from functools import total_ordering @total_ordering class Student: def __init__(self, name, grade): self.name = name self.grade = grade def __eq__(self, other): return self.grade == other.grade def __lt__(self, other): return self.grade < other.grade
Code for : Find slow code in Python (v6)
import cProfile, pstats, timeit # Quick benchmark elapsed = timeit.timeit('sum(range(1000))', number=10_000) print(f'10k runs: {elapsed:.3f}s') # Full profiling cProfile.run('my_function()', 'output.prof') p = pstats.Stats('output.prof').sort_stats('cumulative') p.print_stats(10)
Practical use of I want to understand string template python. in Python (v7)
# str.format msg = 'Hello, {}! You are {} years old.'.format('Alice', 30) # Named placeholders msg2 = '{name} scored {score:.1f}%'.format(name='Bob', score=92.5) # % style msg3 = 'Value: %d, Float: %.2f' % (42, 3.14)
Python 3 What does how to compare objects python look like example code
class Point: def __init__(self, x, y): self.x, self.y = x, y def __eq__(self, other): return isinstance(other, Point) and self.x == other.x and self.y == other.y def __hash__(self): return hash((self.x, self.y))
Python code showing Show me how to all subsets of size r python in . (v4)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
Write a function to demonstrate What is the best way to event listener python (v8)
class EventEmitter: def __init__(self): self._listeners = {} def on(self, event, callback): self._listeners.setdefault(event, []).append(callback) def emit(self, event, *args, **kwargs): for cb in self._listeners.get(event, []): cb(*args, **kwargs)
Python code showing What does timeit python look like in (v8)
import cProfile, pstats, timeit # Quick benchmark elapsed = timeit.timeit('sum(range(1000))', number=10_000) print(f'10k runs: {elapsed:.3f}s') # Full profiling cProfile.run('my_function()', 'output.prof') p = pstats.Stats('output.prof').sort_stats('cumulative') p.print_stats(10)
Explain Demonstrate python sort lambda example in 3. in Python
people = [('Alice', 30), ('Bob', 25), ('Carol', 35)] # Sort by age ascending by_age = sorted(people, key=lambda p: p[1]) # Sort by name descending by_name_desc = sorted(people, key=lambda p: p[0], reverse=True)
Explain What is the best way to python web app flask in Python (v2)
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/hello', methods=['GET']) def hello(): name = request.args.get('name', 'World') return jsonify({'message': f'Hello, {name}!'})
Advanced Explain and show code to format and inspect except Python example (v6)
import traceback try: 1 / 0 except ZeroDivisionError: error_msg = traceback.format_exc() print(f"Captured traceback:\n{error_msg}")
Python snippet: How do I intercept subclass inheritance using __in (v9)
class BaseHandler: registry = {} def __init_subclass__(cls, handler_type=None, **kwargs): super().__init_subclass__(**kwargs) if handler_type: cls.registry[handler_type] = cls