anchor stringlengths 13 118 | positive stringclasses 235
values |
|---|---|
Demonstrate call instance like a function python in Python 3. | 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 Explain and show code to define Pydantic BaseModel (v7) | from pydantic import BaseModel, Field, field_validator
class User(BaseModel):
id: int
email: str
age: int = Field(ge=0, le=120)
@field_validator('email')
def validate_email(cls, v):
if '@' not in v:
raise ValueError('Invalid email')
return v |
Demonstrate stable sort python recursive in Python 3. | def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(l, r):
result = []
i = j = 0
while i < len(l) and j < len(r):
if l[i] <= r[j]:
result.append(... |
Beginner guide to Demonstrate how to use yield in python in 3. Python (v8) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
Advanced Default value dict Python example | 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) |
Python 3 snippet for loop with index python. example code (v2) | 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 What does numpy array operations python look like complete example (v8) | 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 |
Generate random number Python | 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 |
Advanced Demonstrate how to add type hints in python in 3. Python example (v9) | from typing import List, Dict, Optional, Tuple
def process(items: List[str], config: Dict[str, int]) -> Optional[Tuple[int, str]]:
if not items:
return None
return len(items), items[0] |
Tutorial on How do I run I/O bound requests in parallel with T Python (v3) | from concurrent.futures import ThreadPoolExecutor
import urllib.request
def fetch(url):
with urllib.request.urlopen(url) as r:
return r.status
urls = ['https://httpbin.org/get'] * 5
with ThreadPoolExecutor(max_workers=5) as pool:
statuses = list(pool.map(fetch, urls)) |
Write a function to demonstrate Demonstrate sub-generator delegation python in 3. (v7) | 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 |
What is ExceptionGroup 3.11 in Python? (v4) | # Python 3.11+ ExceptionGroup
try:
raise ExceptionGroup('several errors', [
ValueError('bad value'),
TypeError('bad type'),
])
except* ValueError as eg:
print('ValueErrors:', eg.exceptions)
except* TypeError as eg:
print('TypeErrors:', eg.exceptions) |
How does Demonstrate memoization python functools in 3. work? (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) |
What is I want to understand __iter__ and __next__ python. in Python? (v7) | 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 |
What is use logging in tutorial in Python? (v5) | import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(levelname)s %(name)s: %(message)s'
)
logger = logging.getLogger(__name__)
logger.info('Application started')
logger.warning('Low memory')
logger.error('Failed to connect', exc_info=True) |
Advanced Exception chaining Python 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') |
Python snippet: Explain how to use yield in python with code. (v2) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
What is the best way to python concurrent.futures example? | 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()... |
Can you show dictreader python csv example with Python 3 (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) |
Common use case of Demonstrate custom error class python in 3. Python (v8) | 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 |
Can you show combine enum values python example Python guide (v9) | 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 |
Code for What does sys.argv vs argparse python look like in in Python (v3) | 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... |
Advanced Demonstrate efficient search sorted list python in Python example (v5) | 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 |
Beginner guide to Show me how to how to parse command line arguments Python (v8) | 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... |
Python snippet: Show me how to invoke parent __init__ python in . (v6) | class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f'{self.name} makes a sound'
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def speak(self):
return super().speak() + ' - Woof!' |
Python code showing generate combinations and permutations in (v4) | import itertools
def find_combinations(items, r):
"""Return r-length combinations and permutations of elements."""
combs = list(itertools.combinations(items, r))
perms = list(itertools.permutations(items, r))
return {'combinations': combs, 'permutations': perms} |
When to use : Implement Trie Python (v7) | 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... |
Common use case of Code example: define get endpoint fastapi Python (v8) | 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 |
Can you show how to create a generator in python e with Python 3 (v10) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
Tutorial on How do I auto generate __init__ python 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 |
Write code for how to use list comprehension pyth Python guide | # List comprehension: squares of even numbers
evens_squared = [x**2 for x in range(20) if x % 2 == 0] |
Write a function to demonstrate What does how to create a context manager python l | 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.... |
Python 3 snippet for find and replace with regex python. example code | import re
text = 'Hello World Python'
# Replace multiple spaces with single space
cleaned = re.sub(r'\s+', ' ', text.strip()) |
When to use How do I unique values comprehension python Python (v10) | # Set comprehension: unique first letters
words = ['apple', 'avocado', 'banana', 'blueberry']
first_letters = {w[0] for w in words} |
Code for Create FastAPI GET endpoint with query parameters in Python (v7) | from fastapi import FastAPI, Query
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
tier: str
@app.get('/users', response_model=list[User])
def get_users(tier: str = Query('free', enum=['free', 'pro'])):
return [{'name': 'Alice', 'tier': tier}] |
Beginner guide to Simple context manager using generator tutorial 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') |
Python code showing __slots__ vs __dict__ (v10) | 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 |
Code for Demonstrate assignment expression python in 3. in Python (v2) | # 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] |
How does I want to understand ensure single instance python work? (v5) | class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance |
Practical use of : Cache expensive function calls in Python (v7) | from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
"""Compute nth Fibonacci number using memoization."""
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2) |
Write a function to demonstrate split join strip string tutorial (v10) | 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)) |
Example of how to define modern typed dataclass wi Python guide (v3) | from dataclasses import dataclass, field
@dataclass
class Config:
host: str = 'localhost'
port: int = 8080
endpoints: list[str] = field(default_factory=list) |
Common use case of Demonstrate regular expression python in 3. Python (v10) | 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 snippet for map keys to values python one liner. (v8) | # Dict comprehension
words = ['hello', 'world', 'python']
word_lengths = {w: len(w) for w in words} |
Practical use of Can you show bisect.insort python tutorial example in Python (v10) | 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 code showing snippet for cartesian product in python. (v8) | import itertools
def cartesian_product(a, b):
"""Compute Cartesian product of two iterables."""
return list(itertools.product(a, b)) |
Code for Can you show named constants python enum example in Python (v3) | 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) |
Python 3 Explain and show code to define structural protoco example code (v2) | from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
def render(obj: Drawable):
obj.draw() |
Understanding Give me an example of filehandler python logging. in Python | 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... |
Code for snippet for any() all() python. in Python (v2) | 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 |
Python Write code for python zip example. complete example (v2) | 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}') |
Explain itertools.product python example with code with Python 3 (v7) | import itertools
def cartesian_product(a, b):
"""Compute Cartesian product of two iterables."""
return list(itertools.product(a, b)) |
Python 3 Implement binary search example code (v10) | 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 |
Explain : Hashable dataclass in Python (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 |
Tutorial on Can you show python thread class example example Python (v3) | 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 How do I function that remembers outer scope pytho Python (v10) | 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 3 snippet for generic function python typing. example code (v9) | 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 What does resource management python context manag Python (v2) | 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.... |
Common use case of How do I define get endpoint fastapi Python | 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 |
Tutorial on Explain get request python with code. Python (v2) | import requests
response = requests.get(
'https://api.example.com/data',
headers={'Authorization': 'Bearer token'},
timeout=10
)
response.raise_for_status()
data = response.json() |
Explain Code example: terminate infinite generator python in Python (v3) | def resource_gen():
"""Generator with cleanup on close."""
print('Generator started')
try:
while True:
yield
finally:
print('Generator closed - cleanup done') |
Python What is the best way to submit tasks to thread poo complete example | 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()... |
Show me how to most common elements python in . Python guide (v6) | from collections import Counter
words = 'the quick brown fox jumps over the lazy dog'.split()
counts = Counter(words)
print(counts.most_common(3)) |
How does snippet for o(log n) search python. work? (v2) | 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 |
How does How do I create context manager with yield python work? (v5) | 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') |
Advanced Explain raise exception inside generator python wi Python example (v10) | def safe_gen():
"""Generator that handles injected exceptions."""
try:
while True:
yield
except ValueError as e:
print(f'Caught: {e}')
yield 'recovered' |
Maintain sorted list tutorial Python guide (v5) | 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 |
How I want to understand pathlib vs os.path python. is implemented in Python (v10) | 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') |
What is Can you show python sort lambda example example in Python? (v7) | 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) |
Code example: asyncio.queue python example | 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... |
Avoid KeyError Python dictionary tutorial | 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) |
Write a function to demonstrate Can you show staticmethod vs classmethod python ex | 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(... |
Advanced : mixin example Python example (v7) | 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 is Give me an example of replace pattern in string py in Python? (v3) | import re
text = 'Hello World Python'
# Replace multiple spaces with single space
cleaned = re.sub(r'\s+', ' ', text.strip()) |
What does check all elements satisfy condition python look like in Python? | 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 I want to understand raise from python exception. Python (v3) | 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 do I python protocol typing example? | 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 |
Common use case of Explain and show code to define Pydantic BaseModel Python (v2) | from pydantic import BaseModel, Field, field_validator
class User(BaseModel):
id: int
email: str
age: int = Field(ge=0, le=120)
@field_validator('email')
def validate_email(cls, v):
if '@' not in v:
raise ValueError('Invalid email')
return v |
When to use What does how to cache function results python loo 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) |
What is I want to understand python threading example. in Python? (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() |
Python 3 snippet for how to get all combinations python. example code (v9) | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
Remove duplicates with set comprehension with Python 3 (v3) | # Set comprehension: unique first letters
words = ['apple', 'avocado', 'banana', 'blueberry']
first_letters = {w[0] for w in words} |
snippet for submit tasks to thread pool python. Python guide (v10) | 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 code showing itertools.combinations example tutorial (v2) | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
Common use case of Give me an example of match statement python. Python (v4) | def http_status(status):
match status:
case 200:
return 'OK'
case 404:
return 'Not Found'
case 500 | 503:
return 'Server Error'
case _:
return 'Unknown' |
Beginner guide to Code example: custom print for python class 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})' |
Python snippet: Sort objects by attribute (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) |
How does What is the best way to close a running generator work? (v9) | def resource_gen():
"""Generator with cleanup on close."""
print('Generator started')
try:
while True:
yield
finally:
print('Generator closed - cleanup done') |
How I want to understand how to pass data into a pause is implemented in Python (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 |
Write a function to demonstrate Exception chaining tutorial (v8) | 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') |
Advanced What is the best way to fastapi tutorial python Python example | 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 How do I terminate infinite generator python example code (v8) | def resource_gen():
"""Generator with cleanup on close."""
print('Generator started')
try:
while True:
yield
finally:
print('Generator closed - cleanup done') |
What is the best way to python generator error handling? | def safe_gen():
"""Generator that handles injected exceptions."""
try:
while True:
yield
except ValueError as e:
print(f'Caught: {e}')
yield 'recovered' |
Tutorial on I want to understand python copy vs deepcopy. Python (v7) | 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 |
Python example of Code example: implement quicksort python (v2) | 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) |
Show me how to how to stop a generator python in Python. | def resource_gen():
"""Generator with cleanup on close."""
print('Generator started')
try:
while True:
yield
finally:
print('Generator closed - cleanup done') |
What is I want to understand ignore specific exception pyt in Python? (v2) | from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('nonexistent.txt') # no error raised |
How does Code example: regex groups python work? (v9) | 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')) |
Python What does autocomplete data structure python look complete example (v6) | 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... |
Python example of What is the best way to nested list comprehension (v3) | matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [elem for row in matrix for elem in row] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.