anchor
stringlengths
13
118
positive
stringclasses
235 values
Common use case of I want to understand setup and teardown pytest. Python (v5)
import pytest @pytest.fixture def sample_data(): return {'name': 'Alice', 'age': 30} def test_name(sample_data): assert sample_data['name'] == 'Alice' def test_age(sample_data): assert sample_data['age'] == 30
Write code for python pickle module example. Python guide (v6)
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)
Tutorial on Code example: maintain sorted list python Python (v3)
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
Write a function to demonstrate Demonstrate how to use threads in python in 3. (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()
Python snippet: Can you show ensure single instance python example
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance
What is Can you show submit form data python requests exam in Python? (v8)
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: Speed up recursive function Python caching
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)
Write a function to demonstrate Give me an example of filehandler python logging. (v3)
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...
Python example of Code example: write to file python
# 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!')
Python snippet: Code example: lazy list comprehension python (v9)
# Generator expression - memory efficient data = range(1_000_000) total = sum(x**2 for x in data if x % 2 == 0)
Practical use of snippet for how to make python class iterable with in Python (v7)
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]
Tutorial on Give me an example of quicksort algorithm python. Python (v4)
def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right)
Beginner guide to Code example: __get__ __set__ __delete__ python Python (v3)
class Positive: """Descriptor that enforces positive values.""" def __set_name__(self, owner, name): self.name = name def __get__(self, obj, objtype=None): return getattr(obj, f'_{self.name}', None) def __set__(self, obj, value): if value <= 0: raise ValueError(f'{s...
Advanced bisect module example Python example (v7)
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
Understanding What is the best way to filehandler python logging in Python (v2)
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...
Tutorial on Code example: python protocol typing example Python (v7)
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 What does python math.floor ceil round look like i Python (v10)
import math print(math.sqrt(16)) # 4.0 print(math.floor(3.7)) # 3 print(math.ceil(3.2)) # 4 print(math.log(100, 10)) # 2.0 print(math.pi, math.e) # constants print(math.factorial(5)) # 120
Practical use of How do I how to use pathlib python in Python
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')
Python snippet: Explain find and replace with regex python with co (v9)
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
: Map keys to values one liner with Python 3 (v3)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
Code for Code example: transform list with map python in Python
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)
Explain What does how to suppress exceptions python look l in Python (v4)
from contextlib import suppress with suppress(FileNotFoundError): os.remove('nonexistent.txt') # no error raised
Beginner guide to create a simple generator function with yield in p Python (v8)
def count_up_to(max_val): """Yield integers sequentially up to a maximum value.""" count = 1 while count <= max_val: yield count count += 1
Beginner guide to Code example: itertools.groupby python example Python
import itertools def group_consecutive(lst): """Group consecutive equal elements.""" return [(k, list(v)) for k, v in itertools.groupby(lst)]
Python example of Replace pattern in string (v2)
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
Python 3 Can you show terminate infinite generator python e example code
def resource_gen(): """Generator with cleanup on close.""" print('Generator started') try: while True: yield finally: print('Generator closed - cleanup done')
Python How do I memoization python functools complete example (v2)
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 What does python optional vs union look like in in Python? (v6)
from typing import Union def to_int(val: Union[str, float, int]) -> int: """Convert string, float or int to int.""" return int(val)
Advanced Can you show yield from keyword python example exa Python example (v8)
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
When to use set comprehension example Python
# Set comprehension: unique first letters words = ['apple', 'avocado', 'banana', 'blueberry'] first_letters = {w[0] for w in words}
What is What does assignment expression python look like i in Python? (v6)
# 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]
What is : Lazy list comprehension in Python? (v4)
# Generator expression - memory efficient data = range(1_000_000) total = sum(x**2 for x in data if x % 2 == 0)
Python 3 Code example: common python string methods example code (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))
Advanced Write code for staticmethod vs classmethod python Python example (v2)
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(...
Explain snippet for mutex python threading. in Python (v2)
import threading class SafeCounter: """Thread-safe counter using Lock.""" def __init__(self): self._value = 0 self._lock = threading.Lock() def increment(self): with self._lock: self._value += 1 @property def value(self): return self._value
Code for intercept attribute access using __getattr__ and _ in Python (v9)
class DynamicAttributes: def __init__(self): self._data = {} def __getattr__(self, name): if name in self._data: return self._data[name] raise AttributeError(f"No attribute {name}") def __setattr__(self, name, value): if name == '_data': super().__seta...
Write a function to demonstrate How do I how to call parent class method python (v10)
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: Python logging module example
import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s: %(message)s' ) logger = logging.getLogger(__name__) logger.info('Application started') logger.warning('Low memory') logger.error('Failed to connect', exc_info=True)
How does Show me how to how to use enum in python in . work? (v4)
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)
Code for What is the best way to autocomplete data structur in Python (v8)
class TrieNode: def __init__(self): self.children = {} self.is_end = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for ch in word: node = node.children.setdefault(ch, TrieNode()) node.is_end...
Advanced Explain bottom up dp python with code. Python example (v6)
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 Code example: match statement python
def http_status(status): match status: case 200: return 'OK' case 404: return 'Not Found' case 500 | 503: return 'Server Error' case _: return 'Unknown'
Write code for take first n items from generator with Python 3 (v4)
import itertools def take(n, iterable): """Return first n items of an iterable as a list.""" return list(itertools.islice(iterable, n))
Code for Example of how to configure logging with rotating in Python (v3)
import logging from logging.handlers import RotatingFileHandler logger = logging.getLogger('app') logger.setLevel(logging.INFO) handler = RotatingFileHandler('app.log', maxBytes=1_000_000, backupCount=3) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.a...
What is What is the best way to how to stop a generator py in Python? (v2)
def resource_gen(): """Generator with cleanup on close.""" print('Generator started') try: while True: yield finally: print('Generator closed - cleanup done')
Tutorial on Show me how to count occurrences python in . Python (v2)
from collections import Counter words = 'the quick brown fox jumps over the lazy dog'.split() counts = Counter(words) print(counts.most_common(3))
Code example: python combination without repetition
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
Tutorial on What does collections.defaultdict tutorial look li 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)
I want to understand custom sequence python class.
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]
Code for How do I how to mock in python tests in Python (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...
Python Write code for python web app flask. complete example
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 What does decorator factory python look like in complete example (v5)
from functools import wraps def repeat(n): """Decorator factory: repeat function n times.""" def decorator(func): @wraps(func) def wrapper(*args, **kwargs): for _ in range(n): result = func(*args, **kwargs) return result return wrapper return ...
Python code showing Validate input pydantic tutorial (v10)
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 Show me how to double ended queue python in . (v4)
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)
Understanding Can you show parallel processing python example in Python (v4)
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)
Advanced snippet for python requests post example. Python example (v8)
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())
Code example: object creation strategy python
class AnimalFactory: @staticmethod def create(kind: str): animals = {'dog': Dog, 'cat': Cat, 'bird': Bird} cls = animals.get(kind) if cls is None: raise ValueError(f'Unknown animal: {kind}') return cls()
Python 3 What does python unittest example look like in example code (v8)
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()
When to use : Delegating generator Python (v6)
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 Explain generator.send() python tutorial with code (v9)
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 example of How do I autocomplete data structure python (v10)
class TrieNode: def __init__(self): self.children = {} self.is_end = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for ch in word: node = node.children.setdefault(ch, TrieNode()) node.is_end...
Advanced Show me how to exceptiongroup python example in . Python example (v2)
# 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 Graph traversal BFS Python (v6)
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) ...
Beginner guide to What does define get endpoint fastapi look like in Python (v4)
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float @app.get('/items/{item_id}') def get_item(item_id: int): return {'id': item_id} @app.post('/items/') def create_item(item: Item): return item
Give me an example of persist python object to dis Python guide (v2)
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)
Advanced Can you show abc python example example Python example (v9)
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self) -> float: ... @abstractmethod def perimeter(self) -> float: ... class Circle(Shape): def __init__(self, r): self.r = r def area(self): import math; return math.pi * self.r**2 def perimeter...
How Show me how to close a running generator python in is implemented in Python (v3)
def resource_gen(): """Generator with cleanup on close.""" print('Generator started') try: while True: yield finally: print('Generator closed - cleanup done')
Practical use of Give me an example of regex replace python. in Python
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
What is How do I define get endpoint fastapi in Python? (v10)
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float @app.get('/items/{item_id}') def get_item(item_id: int): return {'id': item_id} @app.post('/items/') def create_item(item: Item): return item
Understanding Demonstrate fetch url python in 3. in Python (v2)
import requests response = requests.get( 'https://api.example.com/data', headers={'Authorization': 'Bearer token'}, timeout=10 ) response.raise_for_status() data = response.json()
Python example of Can you show raise custom exception python example (v2)
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
When to use Show me how to python counter example in . Python (v7)
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 Demonstrate python f-string example in 3. Python
name = 'Alice' age = 30 pi = 3.14159 # Basic print(f'Hello, {name}!') # Expression print(f'In 5 years: {age + 5}') # Format spec print(f'Pi = {pi:.2f}') # Repr print(f'{name!r}')
Python suppress exceptions complete example (v3)
from contextlib import suppress with suppress(FileNotFoundError): os.remove('nonexistent.txt') # no error raised
When to use Show me how to rotate list python deque in . Python (v7)
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)
Write a function to demonstrate How do I permission flags python enum (v5)
from enum import Flag, auto class Permission(Flag): READ = auto() WRITE = auto() EXECUTE = auto() ALL = READ | WRITE | EXECUTE user_perm = Permission.READ | Permission.WRITE print(Permission.READ in user_perm) # True
What is How do I trigonometry python in Python? (v5)
import math print(math.sqrt(16)) # 4.0 print(math.floor(3.7)) # 3 print(math.ceil(3.2)) # 4 print(math.log(100, 10)) # 2.0 print(math.pi, math.e) # constants print(math.factorial(5)) # 120
How Show me how to how to use lock in python threading is implemented in Python (v3)
import threading class SafeCounter: """Thread-safe counter using Lock.""" def __init__(self): self._value = 0 self._lock = threading.Lock() def increment(self): with self._lock: self._value += 1 @property def value(self): return self._value
Give me an example of use custom object as dict key python.
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 How does the yield keyword work in Python (v7)
def simple_generator(): """Yield returns a value and preserves function local state for next invocation.""" yield "First" yield "Second" yield "Third"
Explain What does find n smallest python look like in in Python (v10)
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)
Write code for math functions python. with Python 3
import math print(math.sqrt(16)) # 4.0 print(math.floor(3.7)) # 3 print(math.ceil(3.2)) # 4 print(math.log(100, 10)) # 2.0 print(math.pi, math.e) # constants print(math.factorial(5)) # 120
Python snippet: : Function that remembers outer scope (v8)
def make_counter(start=0): """Closure that maintains a counter.""" count = [start] def increment(by=1): count[0] += by return count[0] return increment
Tutorial on How do I list comprehension with two loops Python (v5)
matrix = [[1,2,3],[4,5,6],[7,8,9]] flat = [elem for row in matrix for elem in row]
Common use case of What does dictionary from two lists python look li Python (v2)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
What is Find and replace with regex in Python?
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
Python snippet: Show me how to how to write a decorator in python (v4)
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
Can you show python generator function example example?
def count_up(n): """Generator that yields numbers 0 to n-1.""" for i in range(n): yield i
How How do I when to use classmethod python is implemented in 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(...
Show me how to python generator send method exampl Python guide (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 example of What does decorator that accepts parameters python (v7)
from functools import wraps def repeat(n): """Decorator factory: repeat function n times.""" def decorator(func): @wraps(func) def wrapper(*args, **kwargs): for _ in range(n): result = func(*args, **kwargs) return result return wrapper return ...
Python 3 Code example: array math python numpy example code (v3)
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
Python code showing I want to understand how to use := in python.
# 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]
Give me an example of how to use list comprehensio Python guide (v7)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
Python code showing : Plugin registration __init_subclass__ (v10)
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}
Python code to calculate greatest common divisor and least common multiple using math
import math def gcd_lcm(a, b): g = math.gcd(a, b) l = math.lcm(a, b) return {'gcd': g, 'lcm': l}
Practical use of Write code for dataframe operations python. in Python (v6)
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 snippet for exceptiongroup python example. in Python (v4)
# 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)
Python create custom exception tutorial complete example (v7)
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 Demonstrate object creation strategy python in 3. in Python
class AnimalFactory: @staticmethod def create(kind: str): animals = {'dog': Dog, 'cat': Cat, 'bird': Bird} cls = animals.get(kind) if cls is None: raise ValueError(f'Unknown animal: {kind}') return cls()