anchor
stringlengths
13
118
positive
stringclasses
235 values
Explain Give me an example of python pickle module example in Python (v9)
import pickle data = {'key': [1, 2, 3], 'model': None} # Save with open('data.pkl', 'wb') as f: pickle.dump(data, f) # Load with open('data.pkl', 'rb') as f: loaded = pickle.load(f)
Practical use of Explain bfs algorithm python with code. in Python (v7)
from collections import deque def bfs(graph, start): visited = {start} queue = deque([start]) order = [] while queue: node = queue.popleft() order.append(node) for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) ...
Understanding What is the best way to python string representati in Python (v5)
class Point: def __init__(self, x, y): self.x, self.y = x, y def __repr__(self): return f'Point({self.x!r}, {self.y!r})' def __str__(self): return f'({self.x}, {self.y})'
Explain Swallow exception tutorial in Python
from contextlib import suppress with suppress(FileNotFoundError): os.remove('nonexistent.txt') # no error raised
What is use := in in 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 snippet: Demonstrate python protocol typing example in 3.
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
Code for Give me an example of two-way communication with g in Python (v6)
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 3 What does custom error class python look like in example code (v6)
class ValidationError(Exception): """Raised when input validation fails.""" def __init__(self, field: str, msg: str): self.field = field super().__init__(f'{field}: {msg}') class NetworkError(RuntimeError): """Raised on network failures.""" pass
Explain I want to understand with statement custom class p in Python (v10)
class ManagedFile: """Custom context manager for file handling.""" def __init__(self, name, mode): self.name = name self.mode = mode def __enter__(self): self.file = open(self.name, self.mode) return self.file def __exit__(self, exc_type, exc_val, exc_tb): self....
snippet for python closure example. Python guide (v5)
def make_counter(start=0): """Closure that maintains a counter.""" count = [start] def increment(by=1): count[0] += by return count[0] return increment
Beginner guide to Write code for python group adjacent equal elemen Python
import itertools def group_consecutive(lst): """Group consecutive equal elements.""" return [(k, list(v)) for k, v in itertools.groupby(lst)]
Demonstrate user defined exception python in Python 3.
class ValidationError(Exception): """Raised when input validation fails.""" def __init__(self, field: str, msg: str): self.field = field super().__init__(f'{field}: {msg}') class NetworkError(RuntimeError): """Raised on network failures.""" pass
Code example: maintain sorted list python
import bisect sorted_list = [1, 3, 5, 7, 9] bisect.insort(sorted_list, 4) # insert 4 keeping sorted pos = bisect.bisect_left(sorted_list, 5) # find position of 5
Python: Background task asyncio Python
import asyncio async def background_work(): await asyncio.sleep(2) print('Done') async def main(): """Create and schedule a background task.""" task = asyncio.create_task(background_work()) print('Task created, doing other work') await task
Common use case of Show me how to __iter__ and __next__ python in . 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
Tutorial on Code example: two-way communication with generator Python (v2)
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 Write code for close a running generator python. complete example (v9)
def resource_gen(): """Generator with cleanup on close.""" print('Generator started') try: while True: yield finally: print('Generator closed - cleanup done')
Common use case of : Custom sequence class Python (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]
Understanding @property class example tutorial in Python (v6)
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...
Python 3 Code example: threadpoolexecutor python example code (v5)
from concurrent.futures import ThreadPoolExecutor, as_completed def fetch(url): import time; time.sleep(0.5) return f'result:{url}' with ThreadPoolExecutor(max_workers=5) as ex: futures = {ex.submit(fetch, url): url for url in ['a','b','c']} for fut in as_completed(futures): print(fut.result()...
Python code showing snippet for collections.defaultdict tutorial. (v8)
from collections import defaultdict # Group words by first letter words = ['apple', 'avocado', 'banana', 'blueberry', 'cherry'] groups = defaultdict(list) for word in words: groups[word[0]].append(word)
Code for How do I depth first search traversal on graph wit in Python (v3)
def dfs(graph, node, visited=None): if visited is None: visited = set() visited.add(node) path = [node] for neighbor in graph.get(node, []): if neighbor not in visited: path.extend(dfs(graph, neighbor, visited)) return path
Give me an example of python open file example.
# Read entire file with open('data.txt', 'r', encoding='utf-8') as f: content = f.read() # Write to file with open('output.txt', 'w', encoding='utf-8') as f: f.write('Hello, World!')
How does Explain and show code to use Literal type to restr work? (v2)
from typing import Literal def set_mode(mode: Literal['read', 'write', 'append']): print(f"Opening in {mode} mode")
Advanced I want to understand all subsets of size r python. Python example (v9)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
Python snippet: Can you show decorator using __call__ python examp (v5)
class CountCalls: """Class-based decorator that counts function calls.""" def __init__(self, func): self.func = func self.count = 0 def __call__(self, *args, **kwargs): self.count += 1 return self.func(*args, **kwargs)
How does json module example work?
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 3 Explain singleton pattern python with code. example code (v4)
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance
What is Map keys to values one liner tutorial in Python? (v8)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
Explain Can you show notify subscribers python example in Python (v10)
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)
Write a function to demonstrate Named constants enum
from enum import Enum, auto class Color(Enum): RED = auto() GREEN = auto() BLUE = auto() print(Color.RED) # Color.RED print(Color.RED.value) # 1 for color in Color: print(color.name)
Advanced What does test case python look like in Python example (v10)
import unittest class TestMath(unittest.TestCase): def test_add(self): self.assertEqual(1 + 1, 2) def test_divide_zero(self): with self.assertRaises(ZeroDivisionError): 1 / 0 if __name__ == '__main__': unittest.main()
Python snippet: Can you show binary file format python example (v8)
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)
Code example: write tests with pytest Python guide (v3)
import pytest def add(a, b): return a + b def test_add(): assert add(2, 3) == 5 @pytest.mark.parametrize('a,b,expected', [(1,2,3),(0,0,0),(-1,1,0)]) def test_add_parametric(a, b, expected): assert add(a, b) == expected
Tutorial on snippet for when to use classmethod python. Python
class Date: """Date class demonstrating classmethod and staticmethod.""" def __init__(self, year, month, day): self.year, self.month, self.day = year, month, day @classmethod def from_string(cls, s): """Alternative constructor from 'YYYY-MM-DD' string.""" year, month, day = map(...
Beginner guide to snippet for run cpu bound tasks in parallel python Python (v10)
from multiprocessing import Pool def square(x): return x * x if __name__ == '__main__': with Pool(4) as p: results = p.map(square, range(10)) print(results)
What is How do I simple pytest test python in Python? (v10)
import pytest def add(a, b): return a + b def test_add(): assert add(2, 3) == 5 @pytest.mark.parametrize('a,b,expected', [(1,2,3),(0,0,0),(-1,1,0)]) def test_add_parametric(a, b, expected): assert add(a, b) == expected
Tutorial on Give me an example of memory efficient file readin 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'))
What is Write code for named capture groups python re. in Python? (v2)
import re pattern = re.compile(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})') m = pattern.search('Date: 2024-03-15') if m: print(m.group('year'), m.group('month'), m.group('day'))
Write a function to demonstrate Write code for event listener python.
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)
Practical use of Give me an example of post request python. in Python (v6)
import requests payload = {'name': 'Alice', 'score': 99} resp = requests.post('https://api.example.com/submit', json=payload, timeout=10) resp.raise_for_status() print(resp.json())
Python coroutine yield example
def count_up(n): """Generator that yields numbers 0 to n-1.""" for i in range(n): yield i
Explain Example of how to depth first search traversal on in Python (v9)
def dfs(graph, node, visited=None): if visited is None: visited = set() visited.add(node) path = [node] for neighbor in graph.get(node, []): if neighbor not in visited: path.extend(dfs(graph, neighbor, visited)) return path
Common use case of How do I decorator using __call__ python Python (v9)
class CountCalls: """Class-based decorator that counts function calls.""" def __init__(self, func): self.func = func self.count = 0 def __call__(self, *args, **kwargs): self.count += 1 return self.func(*args, **kwargs)
Python snippet: Write code for save and load python objects. (v4)
import pickle data = {'key': [1, 2, 3], 'model': None} # Save with open('data.pkl', 'wb') as f: pickle.dump(data, f) # Load with open('data.pkl', 'rb') as f: loaded = pickle.load(f)
Practical use of Demonstrate common python string methods in 3. in Python (v7)
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))
snippet for typing.protocol python. with Python 3 (v8)
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
When to use Handle multiple exceptions at once 3.11 Python (v6)
# Python 3.11+ ExceptionGroup try: raise ExceptionGroup('several errors', [ ValueError('bad value'), TypeError('bad type'), ]) except* ValueError as eg: print('ValueErrors:', eg.exceptions) except* TypeError as eg: print('TypeErrors:', eg.exceptions)
Common use case of Can you show breadth first search python example Python (v3)
from collections import deque def bfs(graph, start): visited = {start} queue = deque([start]) order = [] while queue: node = queue.popleft() order.append(node) for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) ...
When to use HTTP GET with headers Python (v8)
import requests response = requests.get( 'https://api.example.com/data', headers={'Authorization': 'Bearer token'}, timeout=10 ) response.raise_for_status() data = response.json()
When to use code to keep priority queue with min-heap operatio Python
import heapq nums = [5, 1, 9, 3, 7] heapq.heapify(nums) heapq.heappush(nums, 2) smallest = heapq.heappop(nums) # 1 top_three = heapq.nlargest(3, nums)
How does code to detect cycle in directed graph using DFS a work? (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...
What is Give me an example of function wrapper python. in Python?
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
Python snippet: Code example: python set comprehension example (v9)
# Set comprehension: unique first letters words = ['apple', 'avocado', 'banana', 'blueberry'] first_letters = {w[0] for w in words}
Beginner guide to Explain use custom object as dict key python with Python (v4)
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))
Write a function to demonstrate : All combinations of multiple lists (v9)
import itertools def cartesian_product(a, b): """Compute Cartesian product of two iterables.""" return list(itertools.product(a, b))
Practical use of Code example: default value dict python in Python (v8)
from collections import defaultdict # Group words by first letter words = ['apple', 'avocado', 'banana', 'blueberry', 'cherry'] groups = defaultdict(list) for word in words: groups[word[0]].append(word)
What is the best way to how to cache function resu Python guide (v8)
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)
What is 3.10 union type hint | tutorial in 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)
Code example: mutable default in dataclass python
from dataclasses import dataclass, field @dataclass class Team: name: str members: list = field(default_factory=list) _id: int = field(default=0, repr=False)
Asynchronous function Python guide (v5)
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}'
Explain code to define modern typed dataclass with default in Python
from dataclasses import dataclass, field @dataclass class Config: host: str = 'localhost' port: int = 8080 endpoints: list[str] = field(default_factory=list)
Beginner guide to : *args **kwargs Python (v3)
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}
yield from keyword Python example
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
Can you show mutable default in dataclass python e with Python 3 (v10)
from dataclasses import dataclass, field @dataclass class Team: name: str members: list = field(default_factory=list) _id: int = field(default=0, repr=False)
Advanced Custom iterator class Python example (v6)
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
I want to understand alternative constructor pytho with Python 3 (v6)
class Date: """Date class demonstrating classmethod and staticmethod.""" def __init__(self, year, month, day): self.year, self.month, self.day = year, month, day @classmethod def from_string(cls, s): """Alternative constructor from 'YYYY-MM-DD' string.""" year, month, day = map(...
Beginner guide to Give me an example of custom iterator class python Python (v2)
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
Beginner guide to Write code for sort objects by attribute python. Python (v7)
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)
Practical use of Show me how to super() in inheritance python in . in Python (v5)
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!'
Python: How to copy dict Python
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
Advanced What does re.sub python example look like in Python example (v5)
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
What is Explain parse json string python with code. in Python? (v3)
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)
Code example: benchmark function python with Python 3 (v2)
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)
Tutorial on : functools.cache example Python (v6)
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)
Python 3 Can you show python generator expression example e example code (v6)
# Generator expression - memory efficient data = range(1_000_000) total = sum(x**2 for x in data if x % 2 == 0)
Python code showing What is the best way to how to make python class i (v6)
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 asyncio.gather example is implemented in Python (v2)
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
Advanced What is the best way to numpy array operations pyt Python example (v2)
import numpy as np a = np.array([1, 2, 3, 4, 5]) b = np.arange(5) c = np.zeros((3, 3)) d = np.ones((2, 4)) print(a * 2) # [2 4 6 8 10] print(a.mean()) # 3.0 print(a @ a) # dot product = 55
Code for What is the best way to python cprofile example in Python (v4)
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)
Code example: memory efficient file reading python with Python 3 (v4)
# Memory-efficient line-by-line reading with open('large_file.txt', encoding='utf-8') as f: for line in f: process(line.rstrip('\n'))
What is implement quicksort divide and conquer in in in Python?
def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] mid = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + mid + quicksort(right)
Code for Give me an example of named capture groups python in Python (v3)
import re pattern = re.compile(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})') m = pattern.search('Date: 2024-03-15') if m: print(m.group('year'), m.group('month'), m.group('day'))
When to use Explain rotate list python deque with code. Python (v5)
from collections import deque dq = deque(maxlen=5) # fixed-size circular buffer for i in range(10): dq.append(i) print(dq) # deque([5, 6, 7, 8, 9], maxlen=5)
Common use case of What does python functools.cache example look like Python (v7)
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)
Python 3 How do I python decorator example example code (v8)
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
How to implement __str__ and __repr__ for custom class representation in Python
class User: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f"User(name={self.name!r}, age={self.age!r})" def __str__(self): return f"{self.name} ({self.age} years old)"
Python 3 snippet for what is a closure in python. example code (v9)
def make_counter(start=0): """Closure that maintains a counter.""" count = [start] def increment(by=1): count[0] += by return count[0] return increment
Python code showing threading example tutorial (v2)
import threading def worker(name): print(f'Thread {name} starting') threads = [threading.Thread(target=worker, args=(i,)) for i in range(5)] for t in threads: t.start() for t in threads: t.join()
How What does python functools.cache example look like is implemented in Python (v9)
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)
Python Can you show structural pattern matching python 3. complete example (v2)
def http_status(status): match status: case 200: return 'OK' case 404: return 'Not Found' case 500 | 503: return 'Server Error' case _: return 'Unknown'
Understanding Give me an example of python web app flask. in Python (v6)
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}!'})
Python code showing code to customize object boolean evaluation using (v10)
class Account: def __init__(self, balance): self.balance = balance def __bool__(self): return self.balance > 0
How call parent class method tutorial is implemented in Python (v8)
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!'
Explain consecutive grouping python with code.
import itertools def group_consecutive(lst): """Group consecutive equal elements.""" return [(k, list(v)) for k, v in itertools.groupby(lst)]
How Write code for unique values comprehension python is implemented in Python (v3)
# Set comprehension: unique first letters words = ['apple', 'avocado', 'banana', 'blueberry'] first_letters = {w[0] for w in words}
Python 3 What does python re module example look like in example code (v3)
import re # Find all email addresses text = 'Contact alice@example.com or bob@test.org' emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', text)
Explain __init_subclass__ example in Python (v4)
class Base: _registry = {} def __init_subclass__(cls, kind=None, **kw): super().__init_subclass__(**kw) if kind: Base._registry[kind] = cls class Dog(Base, kind='dog'): pass class Cat(Base, kind='cat'): pass print(Base._registry) # {'dog': Dog, 'cat': Cat}
Common use case of Explain and show code to define generic class with Python (v4)
from typing import TypeVar, Generic T = TypeVar('T') class Box(Generic[T]): def __init__(self, item: T): self.item = item def get(self) -> T: return self.item
How does use Literal type to restrict parameter to set of e work? (v6)
from typing import Literal def set_mode(mode: Literal['read', 'write', 'append']): print(f"Opening in {mode} mode")