anchor stringlengths 13 118 | positive stringclasses 235
values |
|---|---|
Tutorial on I want to understand processpoolexecutor python us Python (v9) | from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch(url):
import time; time.sleep(0.5)
return f'result:{url}'
with ThreadPoolExecutor(max_workers=5) as ex:
futures = {ex.submit(fetch, url): url for url in ['a','b','c']}
for fut in as_completed(futures):
print(fut.result()... |
Python I want to understand python re module example. complete example (v3) | import re
# Find all email addresses
text = 'Contact alice@example.com or bob@test.org'
emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', text) |
When to use Can you show pathlib vs os.path python example Python (v8) | 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') |
How to handle StopIteration in custom iterator in Python | class FiniteIterator:
def __init__(self, limit):
self.n = 0
self.limit = limit
def __iter__(self):
return self
def __next__(self):
if self.n >= self.limit:
raise StopIteration("Iteration limit reached")
self.n += 1
return self.n |
Code for How do I sort objects by attribute python in Python (v4) | 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) |
Python : Lightweight data object complete example (v8) | from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # access by name |
Code for Can you show enumeration class python example in Python (v8) | from enum import Enum, auto
class Color(Enum):
RED = auto()
GREEN = auto()
BLUE = auto()
print(Color.RED) # Color.RED
print(Color.RED.value) # 1
for color in Color:
print(color.name) |
Advanced Explain limit iterator output python with code. Python example (v10) | import itertools
def take(n, iterable):
"""Return first n items of an iterable as a list."""
return list(itertools.islice(iterable, n)) |
Write a function to demonstrate : Limit iterator output (v9) | import itertools
def take(n, iterable):
"""Return first n items of an iterable as a list."""
return list(itertools.islice(iterable, n)) |
Python Give me an example of singleton pattern python. complete example | class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance |
When to use How do I test case python Python (v7) | import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(1 + 1, 2)
def test_divide_zero(self):
with self.assertRaises(ZeroDivisionError):
1 / 0
if __name__ == '__main__':
unittest.main() |
Python snippet: Demonstrate one liner list transformation python i | # List comprehension: squares of even numbers
evens_squared = [x**2 for x in range(20) if x % 2 == 0] |
Advanced What does how to serialize python objects look lik Python example (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) |
Beginner guide to Code example: python open file example 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!') |
Understanding I want to understand pickle dump and load python. in Python (v5) | 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) |
How does : Sub-generator delegation work? (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 |
Advanced Can you show how to pass data into a paused genera Python example (v3) | 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 code showing Can you show what is yield keyword in python examp (v10) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
When to use Give me an example of speed up recursive function Python (v3) | 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) |
How Explain add behaviour to function without modifyin is implemented in Python | from functools import wraps
def my_decorator(func):
"""Simple decorator that prints before and after."""
@wraps(func)
def wrapper(*args, **kwargs):
print('Before call')
result = func(*args, **kwargs)
print('After call')
return result
return wrapper |
Common use case of Code example: all subsets of size r python Python (v6) | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
What is I want to understand most common elements 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)) |
How Write code for re.match groups python. is implemented in 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')) |
How does How do I what is a decorator in python work? (v5) | from functools import wraps
def my_decorator(func):
"""Simple decorator that prints before and after."""
@wraps(func)
def wrapper(*args, **kwargs):
print('Before call')
result = func(*args, **kwargs)
print('After call')
return result
return wrapper |
Python 3 What is the best way to assert equal python unitte example 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() |
: collections.defaultdict tutorial with Python 3 (v3) | 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) |
Tutorial on Explain how to serialize python objects with code. Python (v5) | 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) |
Python : create asyncio Task complete example (v8) | import asyncio
async def background_work():
await asyncio.sleep(2)
print('Done')
async def main():
"""Create and schedule a background task."""
task = asyncio.create_task(background_work())
print('Task created, doing other work')
await task |
What is Can you show speed up recursive function python ca in Python? (v6) | from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
"""Compute nth Fibonacci number using memoization."""
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2) |
Explain I want to understand python yield from usage. in Python (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 |
Write code for asyncio.create_task example. Python guide (v6) | import asyncio
async def background_work():
await asyncio.sleep(2)
print('Done')
async def main():
"""Create and schedule a background task."""
task = asyncio.create_task(background_work())
print('Task created, doing other work')
await task |
Explain Can you show rotate list python deque example in Python (v9) | 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) |
Explain Explain functional programming python with code. in Python (v7) | 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) |
Common use case of I want to understand file handling python tutorial Python (v8) | # 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 do I what is yield keyword in python with Python 3 (v7) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
Python Show me how to quicksort algorithm python in . complete example (v5) | 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) |
Tutorial on What is the best way to match email address python Python | import re
# Find all email addresses
text = 'Contact alice@example.com or bob@test.org'
emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', text) |
Python Explain python __slots__ vs __dict__ with code. complete example (v9) | 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 Show me how to python walrus operator example in . | # 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 : Prefix tree complete example (v4) | 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... |
What does flask route example python look like in Python? | 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}!'}) |
Common use case of Code example: file handling python tutorial 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!') |
Write a function to demonstrate How do I cache expensive function calls python (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 code showing snippet for pytest fixture example. (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 |
Python example of Two-way communication with generator (v10) | def accumulator():
"""Generator that receives values via send() and accumulates."""
total = 0
while True:
value = yield total
if value is None:
break
total += value |
Beginner guide to : multiprocessing Pool example Python (v5) | 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) |
Python code showing What does decorator using __call__ python look lik (v5) | class CountCalls:
"""Class-based decorator that counts function calls."""
def __init__(self, func):
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
return self.func(*args, **kwargs) |
What is What is the best way to regex groups python in Python? (v4) | 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')) |
Common use case of Explain how to mock in python tests with code. 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 Demonstrate swallow exception python in 3. in Python (v5) | from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('nonexistent.txt') # no error raised |
Python code showing Write code for inject error into python generator (v4) | def safe_gen():
"""Generator that handles injected exceptions."""
try:
while True:
yield
except ValueError as e:
print(f'Caught: {e}')
yield 'recovered' |
Python example of Demonstrate implement quicksort python in 3. (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) |
How do I how to group consecutive items python? | import itertools
def group_consecutive(lst):
"""Group consecutive equal elements."""
return [(k, list(v)) for k, v in itertools.groupby(lst)] |
What is the best way to create list from loop python comprehension? | # List comprehension: squares of even numbers
evens_squared = [x**2 for x in range(20) if x % 2 == 0] |
When to use Demonstrate all subsets of size r python in 3. Python (v9) | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
Python snippet for python threading.lock example. | 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 |
How Demonstrate create objects based on type python in 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() |
Python Write code for how to create custom exception pyt complete example (v9) | 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 Demonstrate flask get post route in 3. example code (v9) | 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}!'}) |
ThreadPoolExecutor Python tutorial | from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch(url):
import time; time.sleep(0.5)
return f'result:{url}'
with ThreadPoolExecutor(max_workers=5) as ex:
futures = {ex.submit(fetch, url): url for url in ['a','b','c']}
for fut in as_completed(futures):
print(fut.result()... |
Python example of How do I make attribute read only python (v4) | 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... |
What is I want to understand extended unpacking python. in Python? (v10) | 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} |
Give me an example of pack unpack binary data python. | 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) |
Python 3 Code example: parametrize pytest example code (v2) | 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 |
Python snippet for python coroutine example. complete example (v8) | 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}' |
Python Demonstrate raise custom exception python in 3. complete example (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 |
Common use case of Write code for generate random number python. Python (v3) | 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 |
Tutorial on Give me an example of simple data container python Python (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 example of Can you show parse csv with header python example (v7) | 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) |
Advanced operator.attrgetter sort Python example (v4) | 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'])) |
Python snippet for python pytest example. complete example (v5) | 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 |
Beginner guide to sys.argv vs argparse 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... |
Code for : Plugin registration __init_subclass__ in Python (v6) | 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} |
Tutorial on Write code for callback registration python. Python (v8) | class EventEmitter:
def __init__(self):
self._listeners = {}
def on(self, event, callback):
self._listeners.setdefault(event, []).append(callback)
def emit(self, event, *args, **kwargs):
for cb in self._listeners.get(event, []):
cb(*args, **kwargs) |
Practical use of __repr__ vs __str__ tutorial in Python (v6) | 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})' |
What is I want to understand handle multiple exceptions at in Python? (v7) | # 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) |
How What is the best way to make python object hashabl is implemented in Python (v10) | 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 snippet: What is the best way to match case with dataclass (v3) | from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
def describe(point):
match point:
case Point(x=0, y=0):
return 'Origin'
case Point(x=0, y=y):
return f'Y-axis at {y}'
case Point(x=x, y=0):
return f'X-axis at {x}'
ca... |
Demonstrate type() as metaclass python in 3. with Python 3 (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 |
Practical use of Code example: validate subclass creation python in Python (v5) | 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: POST request Python | 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()) |
Understanding What does python protocol typing example look like in Python (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 |
Python dataclass list default value complete example (v3) | from dataclasses import dataclass, field
@dataclass
class Team:
name: str
members: list = field(default_factory=list)
_id: int = field(default=0, repr=False) |
Beginner guide to Sub-generator delegation tutorial Python (v9) | 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 snippet: What does breadth first search python look like in | from collections import deque
def bfs(graph, start):
visited = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
... |
Understanding Iterate over lines in file tutorial in Python (v6) | # Memory-efficient line-by-line reading
with open('large_file.txt', encoding='utf-8') as f:
for line in f:
process(line.rstrip('\n')) |
How snippet for notify subscribers python. is implemented in Python (v3) | 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 Can you show itertools.groupby python example exam in Python? | import itertools
def group_consecutive(lst):
"""Group consecutive equal elements."""
return [(k, list(v)) for k, v in itertools.groupby(lst)] |
How does Show me how to variable arguments python function work? (v5) | 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) |
Common use case of Code example: python operator module example Python (v9) | 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 |
Beginner guide to Demonstrate __repr__ vs __str__ python in 3. Python (v3) | 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})' |
Beginner guide to Write code for how to get all combinations python Python (v6) | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
Python snippet: Show me how to custom iterator class python in . (v9) | 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 |
Code for I want to understand map keys to values python one in Python (v7) | # Dict comprehension
words = ['hello', 'world', 'python']
word_lengths = {w: len(w) for w in words} |
Python Flask GET POST route tutorial complete example (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}!'}) |
Python 3 snippet for how to create a closure python. example code (v4) | def make_counter(start=0):
"""Closure that maintains a counter."""
count = [start]
def increment(by=1):
count[0] += by
return count[0]
return increment |
Python Code example: add behaviour with mixin python complete example (v5) | 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 I want to understand swallow exception python. in Python (v5) | from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('nonexistent.txt') # no error raised |
How match statement is implemented in Python (v9) | def http_status(status):
match status:
case 200:
return 'OK'
case 404:
return 'Not Found'
case 500 | 503:
return 'Server Error'
case _:
return 'Unknown' |
Understanding Demonstrate modify outer variable from inner funct in Python (v10) | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.