anchor
stringlengths
13
118
positive
stringclasses
235 values
Advanced How do I accept multiple types python function Python example (v10)
from typing import Union def to_int(val: Union[str, float, int]) -> int: """Convert string, float or int to int.""" return int(val)
Tutorial on How do I suppress specific exceptions safely using Python (v6)
import contextlib import os with contextlib.suppress(FileNotFoundError): os.remove('temporary_file_that_may_not_exist.tmp')
How I want to understand factory design pattern python is implemented in Python (v6)
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()
Explain factory design pattern python with code.
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()
How Dictionary from two lists tutorial is implemented in Python (v6)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
Advanced Demonstrate python struct module example in 3. Python example (v7)
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)
How to write a basic function execution timer decorator in Python
import time from functools import wraps def timeit(func): @wraps(func) def wrapper(*args, **kwargs): start = time.perf_counter() res = func(*args, **kwargs) print(f"{func.__name__} took {(time.perf_counter() - start):.4f}s") return res return wrapper
Show me how to python decorator with arguments in Python guide
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 ...
Write a function to demonstrate Unpack list as function arguments (v2)
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)
Practical use of Show me how to one liner list transformation pytho in Python (v3)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
Advanced code to use TypedDict for type checked dictionary Python example (v8)
from typing import TypedDict class UserPayload(TypedDict): username: str email: str is_admin: bool
Understanding : group adjacent equal elements in Python (v2)
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 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})'
Can you show shuffle list python example?
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 Explain regular expression python with code. complete example (v9)
import re # Find all email addresses text = 'Contact alice@example.com or bob@test.org' emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', text)
Write a function to demonstrate snippet for memory efficient iteration python. (v9)
# Generator expression - memory efficient data = range(1_000_000) total = sum(x**2 for x in data if x % 2 == 0)
Demonstrate most common elements python in Python 3.
from collections import Counter words = 'the quick brown fox jumps over the lazy dog'.split() counts = Counter(words) print(counts.most_common(3))
Python snippet: snippet for string interpolation python. (v5)
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}')
Common use case of What is the best way to reusable mixin class pytho 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
Explain Flask route example tutorial in Python (v8)
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}!'})
Code example: implement for loop support in python class
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
Understanding code to binary search and maintain sorted list usi in Python (v5)
import bisect sorted_list = [10, 20, 30, 40] idx = bisect.bisect_left(sorted_list, 25) # 2 bisect.insort(sorted_list, 25) # [10, 20, 25, 30, 40]
Beginner guide to snippet for python dataclass example. Python (v10)
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
Code for Show me how to python nested loop replacement with in Python (v10)
import itertools def cartesian_product(a, b): """Compute Cartesian product of two iterables.""" return list(itertools.product(a, b))
Understanding Write code for standard deviation python. in Python (v5)
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 example of Write code for custom metaclass python. (v3)
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
Code for What is the best way to build dictionary with comp in Python (v7)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
How does : __slots__ memory optimization work? (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
intercept subclass inheritance using __init_subcla Python guide
class BaseHandler: registry = {} def __init_subclass__(cls, handler_type=None, **kwargs): super().__init_subclass__(**kwargs) if handler_type: cls.registry[handler_type] = cls
Python snippet: What does all subsets of size r python look like i (v10)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
Understanding Best practice to dictionary comprehension with fil in Python (v9)
squares = {x: x**2 for x in range(10) if x % 2 == 0}
How does Can you show generator expression vs list comprehe work? (v8)
# Generator expression - memory efficient data = range(1_000_000) total = sum(x**2 for x in data if x % 2 == 0)
What is the best way to call instance like a funct Python guide (v3)
class Multiplier: def __init__(self, factor): self.factor = factor def __call__(self, x): return x * self.factor double = Multiplier(2) print(double(5)) # 10
How do I python nested function variable?
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
What is What does union type hint python look like in in Python?
from typing import Union def to_int(val: Union[str, float, int]) -> int: """Convert string, float or int to int.""" return int(val)
Python example of Code example: python nested loop replacement with
import itertools def cartesian_product(a, b): """Compute Cartesian product of two iterables.""" return list(itertools.product(a, b))
Beginner guide to Show me how to assert equal python unittest in . Python (v3)
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()
Understanding How do I accept multiple types python function 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)
Python How do I context manager protocol python complete example (v7)
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....
Beginner guide to Give me an example of collections.defaultdict tuto Python (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)
Common use case of Write code for flask route example python. Python (v3)
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 snippet for patch function python unittest.
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...
Write a function to demonstrate Callback registration tutorial (v9)
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)
Tutorial on Code example: thread safe counter python Python (v7)
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
What is Can you show how to cache function results python in Python?
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)
Practical use of What is the best way to collections.counter tutori in Python (v5)
from collections import Counter words = 'the quick brown fox jumps over the lazy dog'.split() counts = Counter(words) print(counts.most_common(3))
Python snippet: What is the best way to resume a function from whe (v6)
def count_up(n): """Generator that yields numbers 0 to n-1.""" for i in range(n): yield i
Advanced Explain call instance like a function python with Python example (v5)
class Multiplier: def __init__(self, factor): self.factor = factor def __call__(self, x): return x * self.factor double = Multiplier(2) print(double(5)) # 10
Advanced dataclass example Python example
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 snippet: How do I how to use __slots__ in python (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
Python example of snippet for @dataclass decorator python. (v5)
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
How Explain python defaultdict example with code. is implemented in Python
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 example: python defaultdict example Python guide
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 How do I super() python example in 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!'
Can you show parse csv with header python example?
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 What is the best way to python metaclass example complete example (v8)
class SingletonMeta(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super().__call__(*args, **kwargs) return cls._instances[cls] class Config(metaclass=SingletonMeta): def __init__(self): self.debug = False
Write a function to demonstrate use dataclass in tutorial (v3)
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
Common use case of Demonstrate currying python in 3. Python (v10)
from functools import partial def power(base, exp): return base ** exp square = partial(power, exp=2) cube = partial(power, exp=3) print(square(4)) # 16 print(cube(3)) # 27
What is Explain close a running generator python with code in Python? (v8)
def resource_gen(): """Generator with cleanup on close.""" print('Generator started') try: while True: yield finally: print('Generator closed - cleanup done')
Tutorial on I want to understand custom print for python class Python (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})'
Code for What is the best way to decorator factory python in 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 snippet: Refactor nested loops using yield from tutorial (v2)
def flatten(nested): """Flatten nested iterables using yield from.""" for item in nested: if hasattr(item, '__iter__') and not isinstance(item, str): yield from flatten(item) else: yield item
Practical use of Operator overloading tutorial in Python (v6)
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})'
Python code showing Give me an example of create objects based on type
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 code showing chain multiple iterables (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 a function to demonstrate Explain python combination without repetition with (v3)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
Python example of snippet for overload + operator python. (v5)
class Vector: def __init__(self, x, y): self.x, self.y = x, y def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __repr__(self): return f'Vector({self.x}, {self.y})'
What is the best way to python list comprehension Python guide (v3)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
Code example: python operator module example with Python 3 (v7)
from operator import itemgetter, attrgetter, mul from functools import reduce items = [('apple', 3), ('banana', 1), ('cherry', 2)] sorted_items = sorted(items, key=itemgetter(1)) product = reduce(mul, [1, 2, 3, 4, 5]) # 120
Python example of Can you show how to read and write json python exa (v7)
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)
Practical use of I want to understand staticmethod vs classmethod p in Python (v5)
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 Demonstrate validate input python pydantic in 3. in Python (v8)
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 3 How do I simple context manager using generator example code (v3)
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')
How does snippet for ordereddict python example. work?
from collections import OrderedDict od = OrderedDict() od['a'] = 1 od['b'] = 2 od.move_to_end('a') # move 'a' to end
Practical use of Explain and show code to implement __str__ and __r in Python (v7)
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)"
Understanding How do I non blocking io python asyncio 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}'
Understanding snippet for duck typing with type hints python. in 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
Write a function to demonstrate Write code for ignore specific exception python. (v5)
from contextlib import suppress with suppress(FileNotFoundError): os.remove('nonexistent.txt') # no error raised
Common use case of snippet for python json module example. Python (v5)
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)
How do I lightweight data object python?
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(3, 4) print(p.x, p.y) # access by name
Understanding Show me how to interface python abc module in . in Python (v4)
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...
What is the best way to python __slots__ memory op with Python 3
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
Code for use threads in in Python (v4)
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 does Demonstrate permission flags python enum in 3. work? (v6)
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
Explain snippet for submit tasks to thread pool python. in Python (v7)
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()...
How does One liner list transformation tutorial work? (v5)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
What does pre-fill function arguments python look with Python 3
from functools import partial def power(base, exp): return base ** exp square = partial(power, exp=2) cube = partial(power, exp=3) print(square(4)) # 16 print(cube(3)) # 27
Python snippet: Example of how to depth first search traversal on (v5)
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
Beginner guide to What does ensure single instance python look like Python (v8)
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance
Beginner guide to Function wrapper Python (v10)
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
Write a function to demonstrate snippet for how to make a class a decorator 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)
Write a function to demonstrate re.sub example tutorial (v5)
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
Python 3 Code example: python zip example example code (v3)
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}')
Python Explain python thread class example with code. complete example (v7)
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()
When to use code to specify union and optional type annotation Python
def parse_id(val: int | str | None) -> str: if val is None: return 'anonymous' return str(val)
Python Write code for autocomplete data structure python complete example (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...
How does Can you show memory efficient class python example work? (v5)
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 example of snippet for permission flags python enum. (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
Explain Show me how to itertools.chain example python in . 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]
Python snippet: Modify outer variable from inner function tutoria (v2)
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