anchor
stringlengths
13
118
positive
stringclasses
235 values
How does snippet for python sort lambda example. work? (v2)
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)
Advanced Best practice to create a closure that maintains s Python example
def make_counter(start=0): count = start def step(): nonlocal count count += 1 return count return step
Python 3 os.environ example tutorial example code (v5)
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')
Explain Show me how to how to create a generator in python in Python (v3)
def count_up(n): """Generator that yields numbers 0 to n-1.""" for i in range(n): yield i
Python example of How do I mock external dependency 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 I want to understand python coroutine example. Python (v9)
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}'
Code example: python bisect module example Python guide (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
Python Explain parametrize pytest with code. complete example (v4)
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
Understanding Show me how to *args python example in . in Python
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)
Understanding Demonstrate python cli argument parser in 3. in Python (v7)
import argparse parser = argparse.ArgumentParser(description='My CLI tool') parser.add_argument('input', help='Input file path') parser.add_argument('-o', '--output', default='out.txt', help='Output file') parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() print(args.input, args.ou...
How does dict comprehension example work? (v6)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
How does What does profile python code performance look lik work? (v10)
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 snippet for heapq.heappush python tutorial. Python (v2)
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)
How does What does restrict attributes with __slots__ pytho work? (v3)
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
Python example of : Standard deviation (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
Practical use of Show me how to list comprehension with two loops i in Python (v8)
matrix = [[1,2,3],[4,5,6],[7,8,9]] flat = [elem for row in matrix for elem in row]
How do I python str.format example?
# 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)
Write a function to demonstrate What is the best way to python string representati (v7)
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})'
Code for What does exceptiongroup python example look like in Python
# 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 snippet for how to copy dict python. complete example
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
How does Explain ordereddict python example with code. work? (v5)
from collections import OrderedDict od = OrderedDict() od['a'] = 1 od['b'] = 2 od.move_to_end('a') # move 'a' to end
Python code showing What does parse csv with header python look like i (v5)
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)
Code example: *args python example
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)
Write Python code for stateful decorator python using class.
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 3 I want to understand how to create generator witho example code (v7)
# Generator expression - memory efficient data = range(1_000_000) total = sum(x**2 for x in data if x % 2 == 0)
Write code for __call__ method python. Python guide (v6)
class Multiplier: def __init__(self, factor): self.factor = factor def __call__(self, x): return x * self.factor double = Multiplier(2) print(double(5)) # 10
Common use case of How do I __len__ and __getitem__ python Python (v4)
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]
Advanced I want to understand __eq__ and __hash__ python ex Python example (v9)
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))
What is What is the best way to what is a closure in pytho in Python? (v7)
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 Create directory pathlib tutorial Python (v5)
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 3 Interface in using Protocol example code (v9)
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 is the best way to two-way communication with Python (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
Python snippet: How do I customize object boolean evaluation using
class Account: def __init__(self, balance): self.balance = balance def __bool__(self): return self.balance > 0
When to use Give me an example of function that remembers oute Python (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
split string Python guide (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))
Python code showing Example of how to define a property with getter se (v6)
class Circle: def __init__(self, radius): self._radius = radius @property def radius(self): return self._radius @radius.setter def radius(self, val): if val <= 0: raise ValueError("Radius must be positive") self._radius = val @radius.deleter def ra...
Beginner guide to What does how to create custom exception python lo Python (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
Write a function to demonstrate BaseModel pydantic tutorial (v6)
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 Explain test case python with code. (v9)
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()
Advanced What is the best way to bfs algorithm python Python example (v10)
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) ...
How does What is the best way to async def python tutorial work? (v4)
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}'
Advanced Give me an example of abstract class python. 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...
Advanced Code example: avoid keyerror python dictionary Python example (v2)
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)
Explain How do I context manager protocol python in Python
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....
What does find n smallest python look like in Python?
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 snippet: How do I lightweight data object python (v2)
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(3, 4) print(p.x, p.y) # access by name
Python snippet: What does yield from in python 3 look like in (v5)
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 How do I generate pseudo random numbers and sample (v3)
import random def lottery(candidates, k=3): random.seed(42) chosen = random.sample(candidates, k) random.shuffle(candidates) return chosen
Show me how to filter list with comprehension python in Python.
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
Python snippet for python exception hierarchy example.
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')
Give me an example of what is a closure in python. Python guide (v7)
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 does Can you show callable class python example work? (v8)
class Multiplier: def __init__(self, factor): self.factor = factor def __call__(self, x): return x * self.factor double = Multiplier(2) print(double(5)) # 10
Code example: map keys to values python one liner Python guide (v6)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
What is Create context manager with yield in Python? (v9)
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')
Practical use of Best practice to create a closure that maintains s in Python (v2)
def make_counter(start=0): count = start def step(): nonlocal count count += 1 return count return step
Write a function to demonstrate Can you show hashable dataclass python example (v6)
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
Code for Code example: python enum flag example in Python (v7)
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
Python code showing How do I all subsets of size r python (v7)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
Give me an example of overload + operator python.
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})'
Understanding code to define modern typed dataclass with default in Python (v6)
from dataclasses import dataclass, field @dataclass class Config: host: str = 'localhost' port: int = 8080 endpoints: list[str] = field(default_factory=list)
How snippet for python test class. is implemented in Python (v9)
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()
How do I __repr__ vs __str__ python Python guide (v9)
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})'
How snippet for function that remembers outer scope py 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
Can you show python zip example example with Python 3 (v8)
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 Give me an example of add behaviour with mixin pyt Python (v4)
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 I want to understand define get endpoint fastapi. 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
Python 3 use dataclass in tutorial example code (v8)
from dataclasses import dataclass @dataclass class Employee: name: str department: str salary: float = 50000.0 def raise_salary(self, percent: float): self.salary *= 1 + percent / 100
Python code showing How do I itertools.groupby python example (v7)
import itertools def group_consecutive(lst): """Group consecutive equal elements.""" return [(k, list(v)) for k, v in itertools.groupby(lst)]
How Code example: python chain iterators together is implemented in Python (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]
Write code for python csv module example. Python guide
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)
Python example of Show me how to python open file example in .
# 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!')
Advanced : combination without repetition Python example (v6)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
Explain make python object hashable with 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 example of Code example: count occurrences python (v6)
from collections import Counter words = 'the quick brown fox jumps over the lazy dog'.split() counts = Counter(words) print(counts.most_common(3))
When to use Explain add behaviour with mixin python with code. Python
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
What does exception chaining python look like in Python guide (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')
Demonstrate group list by key python in Python 3.
import itertools def group_consecutive(lst): """Group consecutive equal elements.""" return [(k, list(v)) for k, v in itertools.groupby(lst)]
Write Python code for interactive generator python.
def accumulator(): """Generator that receives values via send() and accumulates.""" total = 0 while True: value = yield total if value is None: break total += value
How Show me how to descriptor protocol python in . is implemented in Python (v5)
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...
Python example of dataclass field with default factory (v10)
from dataclasses import dataclass, field @dataclass class Team: name: str members: list = field(default_factory=list) _id: int = field(default=0, repr=False)
Python example of Demonstrate how to use regex in python in 3. (v5)
import re # Find all email addresses text = 'Contact alice@example.com or bob@test.org' emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', text)
Beginner guide to I want to understand weakvaluedictionary python. Python (v6)
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
Python 3 I want to understand python frozen dataclass examp example code (v2)
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 Can you show python coroutine send value example complete example (v5)
def accumulator(): """Generator that receives values via send() and accumulates.""" total = 0 while True: value = yield total if value is None: break total += value
How Give me an example of flatten 2d list python one l is implemented in Python (v4)
matrix = [[1,2,3],[4,5,6],[7,8,9]] flat = [elem for row in matrix for elem in row]
Explain Best practice to copy move and delete directory tr in Python (v7)
import shutil shutil.copytree('source_dir', 'backup_dir', dirs_exist_ok=True) shutil.rmtree('backup_dir')
Common use case of : getter setter using property Python (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...
Understanding Demonstrate shuffle list python in 3. in Python (v2)
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
Python How do I save and load python objects complete example (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)
Take first N items from generator tutorial with Python 3 (v2)
import itertools def take(n, iterable): """Return first n items of an iterable as a list.""" return list(itertools.islice(iterable, n))
Python example of What does singleton pattern python look like in (v3)
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance
Write a function to demonstrate format and inspect exception stack trace with trac (v8)
import traceback try: 1 / 0 except ZeroDivisionError: error_msg = traceback.format_exc() print(f"Captured traceback:\n{error_msg}")
Understanding Can you show spread operator python example in Python (v7)
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}
Explain I want to understand python copy vs deepcopy. in Python (v3)
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
Explain and show code to create background task wi Python guide (v4)
import asyncio async def log_activity(msg): await asyncio.sleep(0.1) print(f"Logged: {msg}") async def handle_request(): asyncio.create_task(log_activity("Request received")) return {"status": "ok"}
Python snippet: What is the best way to python nested function var
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
Beginner guide to Code example: simple data container python Python
from dataclasses import dataclass @dataclass class Employee: name: str department: str salary: float = 50000.0 def raise_salary(self, percent: float): self.salary *= 1 + percent / 100
Practical use of code to intercept subclass inheritance using __ini in Python (v7)
class BaseHandler: registry = {} def __init_subclass__(cls, handler_type=None, **kwargs): super().__init_subclass__(**kwargs) if handler_type: cls.registry[handler_type] = cls
How : Hook subclass definition is implemented in Python (v9)
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}
What does pytest conftest fixture look like in with Python 3 (v7)
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