anchor
stringlengths
13
118
positive
stringclasses
235 values
Python Show me how to multiple inheritance mixin python i complete example (v10)
class SerializeMixin: def to_dict(self): return self.__dict__ def to_json(self): import json return json.dumps(self.to_dict()) class User(SerializeMixin): def __init__(self, name, email): self.name = name self.email = email
How does read and write files work?
# 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 code showing Show me how to lightweight data object python in . (v4)
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(3, 4) print(p.x, p.y) # access by name
Write a function to demonstrate What does tabulation approach python look like in (v7)
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]
When to use Pandas read csv tutorial Python (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
Write a function to demonstrate snippet for python generator send method example. (v4)
def accumulator(): """Generator that receives values via send() and accumulates.""" total = 0 while True: value = yield total if value is None: break total += value
Understanding Give me an example of hashable dataclass python. in Python (v9)
from dataclasses import dataclass @dataclass(frozen=True) class Point: x: float y: float p = Point(1.0, 2.0) # p.x = 3.0 # raises FrozenInstanceError
Python Write code for decorator factory python. complete example (v9)
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 ...
Code example: restrict attributes with __slots__ p Python guide (v6)
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
How Explain functional programming python with code. is implemented in Python (v2)
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)
Python 3 I want to understand flask route example python. example code (v4)
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}!'})
What is What does python threading example look like in in Python?
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: How to use async await in Python
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}'
How does Demonstrate call instance like a function python i work? (v9)
class Multiplier: def __init__(self, factor): self.factor = factor def __call__(self, x): return x * self.factor double = Multiplier(2) print(double(5)) # 10
Beginner guide to Show me how to deep copy python in . Python (v9)
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
Understanding : Shuffle list in Python (v9)
import random print(random.randint(1, 100)) # integer [1, 100] print(random.random()) # float [0, 1) print(random.choice(['a','b','c'])) # pick one lst = list(range(10)) random.shuffle(lst) # in-place shuffle sample = random.sample(lst, 3) # 3 unique picks
Understanding What is the best way to yield from keyword python in Python (v10)
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
Give me an example of python combination without r with Python 3 (v10)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
When to use I want to understand python gather coroutines resu Python (v9)
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 Write code for python string representation of ob in Python (v10)
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})'
Demonstrate rotating log file python in 3. with Python 3 (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...
When to use : User defined exception Python (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
Python 3 Give me an example of generator expression vs list example code (v6)
# Generator expression - memory efficient data = range(1_000_000) total = sum(x**2 for x in data if x % 2 == 0)
Understanding How do I *args python example in Python (v4)
def display(*args, **kwargs): for arg in args: print(arg) for key, val in kwargs.items(): print(f'{key}={val}') params = [1, 2, 3] opts = {'sep': ', ', 'end': '\n'} display(*params, **opts)
Python example of What does python typevar example look like in (v7)
from typing import TypeVar, Generic, List T = TypeVar('T') class Stack(Generic[T]): def __init__(self) -> None: self._items: List[T] = [] def push(self, item: T) -> None: self._items.append(item) def pop(self) -> T: return self._items.pop()
Beginner guide to Code example: re.sub python example Python (v3)
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
When to use snippet for reusable test setup python pytest. Python (v8)
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
Explain What does magicmock python example look like in in Python
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...
Understanding snippet for bitwise flags python. in Python (v4)
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
Beginner guide to How do I logical or/and over list python Python (v7)
nums = [2, 4, 6, 8, 10] print(all(n % 2 == 0 for n in nums)) # True - all even print(any(n > 9 for n in nums)) # True - at least one > 9
Common use case of Explain and show code to make async HTTP GET reque Python (v5)
import aiohttp import asyncio async def fetch_json(url): async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.json()
Python example of Explain immutable dataclass python with code. (v4)
from dataclasses import dataclass @dataclass(frozen=True) class Point: x: float y: float p = Point(1.0, 2.0) # p.x = 3.0 # raises FrozenInstanceError
Beginner guide to : Prevent race condition threads Python (v10)
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
Python snippet: generator.throw() method tutorial (v7)
def safe_gen(): """Generator that handles injected exceptions.""" try: while True: yield except ValueError as e: print(f'Caught: {e}') yield 'recovered'
Python : any all example complete example (v6)
nums = [2, 4, 6, 8, 10] print(all(n % 2 == 0 for n in nums)) # True - all even print(any(n > 9 for n in nums)) # True - at least one > 9
How does What does write to file python look like in work? (v3)
# 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!')
What is Give me an example of generator.close() python exa in Python? (v6)
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 I want to understand re.match groups python. Python (v5)
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'))
: str.format example Python guide (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)
Explain Write code for python pickle module example. in Python (v3)
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)
Give me an example of divide and conquer sort python.
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)
Advanced Can you show dictionary from two lists python exam Python example (v3)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
Python code showing What does post request python look like in (v7)
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 How do I create numpy array python complete example (v5)
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
Understanding What is the best way to reduce python object memor in Python (v7)
import sys class WithDict: def __init__(self, x, y): self.x, self.y = x, y class WithSlots: __slots__ = ('x', 'y') def __init__(self, x, y): self.x, self.y = x, y print(sys.getsizeof(WithDict(1,2))) # ~48 bytes print(sys.getsizeof(WithSlots(1,2))) # ~32 bytes
Python code showing Callable class tutorial (v7)
class Multiplier: def __init__(self, factor): self.factor = factor def __call__(self, x): return x * self.factor double = Multiplier(2) print(double(5)) # 10
Python example of requests library example tutorial (v6)
import requests response = requests.get( 'https://api.example.com/data', headers={'Authorization': 'Bearer token'}, timeout=10 ) response.raise_for_status() data = response.json()
Python code to create a closure that maintains state between calls using nonlocal
def make_counter(start=0): count = start def step(): nonlocal count count += 1 return count return step
Python snippet: : Map keys to values one liner (v8)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
What is Code example: unpack list as function arguments py in Python? (v3)
def display(*args, **kwargs): for arg in args: print(arg) for key, val in kwargs.items(): print(f'{key}={val}') params = [1, 2, 3] opts = {'sep': ', ', 'end': '\n'} display(*params, **opts)
When to use What is the best way to unique values comprehensio Python (v9)
# Set comprehension: unique first letters words = ['apple', 'avocado', 'banana', 'blueberry'] first_letters = {w[0] for w in words}
Practical use of What does callback registration python look like i 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)
What is Show me how to binary search algorithm python in . in Python?
def binary_search(arr, target): lo, hi = 0, len(arr) - 1 while lo <= hi: mid = (lo + hi) // 2 if arr[mid] == target: return mid elif arr[mid] < target: lo = mid + 1 else: hi = mid - 1 return -1
Python snippet: Explain python __slots__ memory optimization with (v2)
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
When to use Demonstrate how to use queue in asyncio python in 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 : Unpack list into variables Python (v4)
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}
Advanced What does speed up recursive function python cachi Python example (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)
Python list comprehension example
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
When to use I want to understand python generator cleanup on c Python (v9)
def resource_gen(): """Generator with cleanup on close.""" print('Generator started') try: while True: yield finally: print('Generator closed - cleanup done')
Advanced I want to understand how to use queue in asyncio p Python example (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...
Write a function to demonstrate Write code for simple pytest test python. (v7)
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
How do I sorted() with key 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)
What does filter list python look like 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)
How Show me how to make python object printable in . is implemented in Python (v8)
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})'
Advanced Explain lightweight data object python with code. Python example (v10)
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(3, 4) print(p.x, p.y) # access by name
Beginner guide to Explain cache expensive function calls python with Python (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)
When to use itertools.groupby example Python
import itertools def group_consecutive(lst): """Group consecutive equal elements.""" return [(k, list(v)) for k, v in itertools.groupby(lst)]
Python 3 *args example tutorial example code
def display(*args, **kwargs): for arg in args: print(arg) for key, val in kwargs.items(): print(f'{key}={val}') params = [1, 2, 3] opts = {'sep': ', ', 'end': '\n'} display(*params, **opts)
When to use itertools.combinations example Python (v6)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
Python Explain metaclass __new__ python with code. complete example (v4)
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
When to use How do I variance python statistics Python (v7)
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
Python: Encapsulate state with closure Python
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 snippet: Explain how to use property decorator python with (v7)
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 sort by multiple keys python example (v9)
from operator import attrgetter, itemgetter people = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Carol', 'age': 30}] # Sort by age then name sorted_people = sorted(people, key=lambda p: (p['age'], p['name']))
Tutorial on What is the best way to persist python object to d Python (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)
Advanced try except else finally tutorial Python example (v5)
def divide(a, b): try: return a / b except ZeroDivisionError as e: raise ValueError('b cannot be zero') from e except TypeError: raise else: print('Success') finally: print('Always runs')
How does Code example: raise from python exception work? (v2)
def divide(a, b): try: return a / b except ZeroDivisionError as e: raise ValueError('b cannot be zero') from e except TypeError: raise else: print('Success') finally: print('Always runs')
Python Code example: regex replace python complete example (v6)
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
How does I want to understand find slow code python. work? (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)
Python 3 I want to understand how to read environment varia example code (v4)
import os from dotenv import load_dotenv load_dotenv() # reads .env file DB_URL = os.environ['DATABASE_URL'] API_KEY = os.getenv('API_KEY', 'default-key')
Python code showing Explain limit iterator output python with code. (v2)
import itertools def take(n, iterable): """Return first n items of an iterable as a list.""" return list(itertools.islice(iterable, n))
Python Demonstrate default value dict python in 3. complete example (v6)
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)
How Memory efficient iteration is implemented in Python (v7)
# Generator expression - memory efficient data = range(1_000_000) total = sum(x**2 for x in data if x % 2 == 0)
Write a function to demonstrate Iterate two lists simultaneously tutorial (v6)
names = ['Alice', 'Bob', 'Carol'] scores = [95, 87, 92] # zip: pair elements for name, score in zip(names, scores): print(f'{name}: {score}') # enumerate: add index for i, name in enumerate(names, start=1): print(f'{i}. {name}')
When to use I want to understand read only dataclass python. Python (v9)
from dataclasses import dataclass @dataclass(frozen=True) class Point: x: float y: float p = Point(1.0, 2.0) # p.x = 3.0 # raises FrozenInstanceError
Write a function to demonstrate Can you show python walrus operator example exampl (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]
Python 3 What is the best way to convert dict to json pytho example code (v2)
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 How do I python enum flag example
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
Understanding Code example: save and load python objects in Python (v8)
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 What is the best way to unittest.mock patch python Python
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...
Tutorial on : Regular expression Python (v8)
import re # Find all email addresses text = 'Contact alice@example.com or bob@test.org' emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', text)
Python code showing What does python optional vs union look like in (v5)
from typing import Union def to_int(val: Union[str, float, int]) -> int: """Convert string, float or int to int.""" return int(val)
snippet for re.sub python example. with Python 3 (v10)
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
Python I want to understand filter rows pandas python. complete example (v9)
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
Python example of I want to understand reusable mixin class python. (v9)
class SerializeMixin: def to_dict(self): return self.__dict__ def to_json(self): import json return json.dumps(self.to_dict()) class User(SerializeMixin): def __init__(self, name, email): self.name = name self.email = email
Beginner guide to Show me how to how to read and write files python Python (v6)
# 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 I want to understand how to create generator witho is implemented in Python (v10)
# Generator expression - memory efficient data = range(1_000_000) total = sum(x**2 for x in data if x % 2 == 0)
Understanding Give me an example of memory efficient file readin in Python (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'))
Common use case of mock in tests Python (v7)
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...
Common use case of *args **kwargs tutorial Python (v2)
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}