anchor stringlengths 13 118 | positive stringclasses 235
values |
|---|---|
Explain I want to understand object creation strategy pyth 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 python rest api with fastapi. complete 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 |
When to use Explain create pandas dataframe python with code. Python (v3) | import pandas as pd
df = pd.read_csv('data.csv')
# Filter
high_salary = df[df['salary'] > 100_000]
# Group
avg_by_dept = df.groupby('department')['salary'].mean()
# New column
df['bonus'] = df['salary'] * 0.10 |
How does What does nonlocal keyword python example look lik work? (v8) | 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 |
Show me how to mergesort algorithm python in . Python guide (v2) | 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(... |
When to use Can you show rotate list python deque example Python (v3) | 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 Give me an example of operator overloading python. in Python (v4) | 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})' |
Code for Show me how to python f-string example in . in Python (v2) | 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}') |
What is Write code for python protocol typing example. in Python? (v10) | 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 |
How does Explain python pickle module example with code. work? (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 do I how to make python object callable Python guide (v9) | class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
double = Multiplier(2)
print(double(5)) # 10 |
What does itertools.groupby python example look like in Python? | import itertools
def group_consecutive(lst):
"""Group consecutive equal elements."""
return [(k, list(v)) for k, v in itertools.groupby(lst)] |
Intercept attribute access using __getattr__ and _ with Python 3 (v4) | class DynamicAttributes:
def __init__(self):
self._data = {}
def __getattr__(self, name):
if name in self._data:
return self._data[name]
raise AttributeError(f"No attribute {name}")
def __setattr__(self, name, value):
if name == '_data':
super().__seta... |
How do I python decorator example? | 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 Give me an example of python threading.lock exampl complete example (v5) | 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 |
Code example: python-dotenv load .env file Python guide (v8) | import os
from dotenv import load_dotenv
load_dotenv() # reads .env file
DB_URL = os.environ['DATABASE_URL']
API_KEY = os.getenv('API_KEY', 'default-key') |
Python Demonstrate destructuring in python match in 3. complete example (v8) | 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... |
How do I typing.protocol python Python guide (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 |
How do I how to create a generator in python Python guide (v9) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
Practical use of Counter example in Python (v7) | 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 Can you show itertools.combinations example exampl work? (v3) | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
Explain I want to understand vectorized operations numpy. in Python (v3) | import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = np.arange(5)
c = np.zeros((3, 3))
d = np.ones((2, 4))
print(a * 2) # [2 4 6 8 10]
print(a.mean()) # 3.0
print(a @ a) # dot product = 55 |
Understanding Count occurrences of items and find top N with col in Python (v9) | from collections import Counter
words = ['apple', 'banana', 'apple', 'orange', 'apple', 'banana']
counts = Counter(words)
most_common = counts.most_common(2) # [('apple', 3), ('banana', 2)] |
Python example of I want to understand filter rows pandas python. | import pandas as pd
df = pd.read_csv('data.csv')
# Filter
high_salary = df[df['salary'] > 100_000]
# Group
avg_by_dept = df.groupby('department')['salary'].mean()
# New column
df['bonus'] = df['salary'] * 0.10 |
How Submit tasks to thread pool tutorial is implemented in Python | 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 What is the best way to python __slots__ vs __dict is implemented in Python (v2) | 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 |
How Can you show how to use queue in asyncio python ex is implemented in Python (v9) | import asyncio
async def producer(queue):
for i in range(5):
await queue.put(i)
await asyncio.sleep(0.1)
async def consumer(queue):
while True:
item = await queue.get()
print(f'Consumed {item}')
queue.task_done()
async def main():
q = asyncio.Queue()
await asyn... |
Write code for how to create a context manager py with Python 3 (v9) | 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 snippet: I want to understand magicmock python example. (v3) | 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... |
Python example of Explain python cli argument parser with code. (v6) | 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... |
Common use case of Give me an example of refactor nested loops using Python (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 |
How Plugin registration __init_subclass__ 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} |
Python code showing snippet for group by pandas python. (v6) | import pandas as pd
df = pd.read_csv('data.csv')
# Filter
high_salary = df[df['salary'] > 100_000]
# Group
avg_by_dept = df.groupby('department')['salary'].mean()
# New column
df['bonus'] = df['salary'] * 0.10 |
Python example of How do I run multiple coroutines concurrently usin (v6) | import asyncio
async def fetch_data(id, delay):
await asyncio.sleep(delay)
return f"Data {id}"
async def main():
results = await asyncio.gather(fetch_data(1, 0.2), fetch_data(2, 0.4))
return results |
Show me how to read only dataclass python in Python. | 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 |
How Show me how to dynamic programming python example is implemented in Python (v9) | def fib_dp(n):
"""Fibonacci via bottom-up dynamic programming."""
if n < 2:
return n
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n] |
Give me an example of python walrus operator examp Python guide (v7) | # 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] |
Understanding Write code for how to use __slots__ in python. in Python (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 |
Practical use of Demonstrate how to copy dict python in 3. 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 |
Write a function to demonstrate Can you show alternative constructor python classm | 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(... |
: generator error handling with Python 3 (v3) | def safe_gen():
"""Generator that handles injected exceptions."""
try:
while True:
yield
except ValueError as e:
print(f'Caught: {e}')
yield 'recovered' |
Practical use of I want to understand pickle dump and load python. in Python (v10) | 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) |
Write a function to demonstrate What does lazy list comprehension python look like | # Generator expression - memory efficient
data = range(1_000_000)
total = sum(x**2 for x in data if x % 2 == 0) |
Flask GET POST route tutorial with Python 3 (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}!'}) |
What is the best way to functional operators pytho with Python 3 (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 |
Python 3 Notify subscribers example code (v10) | class EventEmitter:
def __init__(self):
self._listeners = {}
def on(self, event, callback):
self._listeners.setdefault(event, []).append(callback)
def emit(self, event, *args, **kwargs):
for cb in self._listeners.get(event, []):
cb(*args, **kwargs) |
What is code to write a decorator that validates argument in Python? (v2) | from functools import wraps
def enforce_types(**expected_types):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for name, val in kwargs.items():
if name in expected_types and not isinstance(val, expected_types[name]):
raise TypeError(... |
Explain except* python syntax with code. Python guide (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) |
Code for Explain and show code to run multiple coroutines c in Python (v6) | import asyncio
async def fetch_data(id, delay):
await asyncio.sleep(delay)
return f"Data {id}"
async def main():
results = await asyncio.gather(fetch_data(1, 0.2), fetch_data(2, 0.4))
return results |
Python example of Can you show unpack list as function arguments pyt (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) |
Practical use of Show me how to python generator error handling in in Python (v3) | def safe_gen():
"""Generator that handles injected exceptions."""
try:
while True:
yield
except ValueError as e:
print(f'Caught: {e}')
yield 'recovered' |
Practical use of snippet for how to create a context manager python in Python (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.... |
Understanding What is the best way to weakvaluedictionary python in Python (v8) | 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 |
Understanding snippet for __len__ and __getitem__ python. in Python (v7) | 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] |
Python code showing How do I contextlib.suppress python example (v2) | from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('nonexistent.txt') # no error raised |
Python 3 Show me how to simple rest api flask python in . example code (v2) | 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 Explain take first n items from generator python w Python (v9) | import itertools
def take(n, iterable):
"""Return first n items of an iterable as a list."""
return list(itertools.islice(iterable, n)) |
Iterate over lines in file Python | # Memory-efficient line-by-line reading
with open('large_file.txt', encoding='utf-8') as f:
for line in f:
process(line.rstrip('\n')) |
Python Show me how to producer consumer asyncio python in complete example (v9) | 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... |
How does Explain python math module example with code. work? (v2) | import math
print(math.sqrt(16)) # 4.0
print(math.floor(3.7)) # 3
print(math.ceil(3.2)) # 4
print(math.log(100, 10)) # 2.0
print(math.pi, math.e) # constants
print(math.factorial(5)) # 120 |
How does Write code for how to pass arguments to a decorat work? (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 ... |
How do I producer consumer asyncio python? | 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... |
Python Show me how to how to read environment variables p complete example | 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 python optional vs union with code. with Python 3 (v2) | from typing import Union
def to_int(val: Union[str, float, int]) -> int:
"""Convert string, float or int to int."""
return int(val) |
Python code showing What is the best way to how to delegate to a sub-g | 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 python set comprehension example (v4) | # Set comprehension: unique first letters
words = ['apple', 'avocado', 'banana', 'blueberry']
first_letters = {w[0] for w in words} |
What does decorator factory python look like in Python? | 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 ... |
Tutorial on snippet for functools.reduce python. Python (v2) | from functools import reduce
nums = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
total = reduce(lambda a, b: a + b, nums) |
Python How do I suppress specific exceptions safely using complete example (v8) | import contextlib
import os
with contextlib.suppress(FileNotFoundError):
os.remove('temporary_file_that_may_not_exist.tmp') |
Practical use of Write code for how to use queue in asyncio python in Python (v3) | 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... |
Python example of Give me an example of python lru_cache decorator e (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) |
Explain I want to understand itemgetter attrgetter python. in Python (v8) | 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 |
Advanced Explain force subclass to implement method python Python example | 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... |
Python Explain encapsulate state with closure python with complete example (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 |
Beginner guide to Can you show parallel processing python example Python (v7) | 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 What is the best way to python multiprocessing poo complete example (v6) | 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) |
Understanding What is the best way to *args python example in Python (v3) | def display(*args, **kwargs):
for arg in args:
print(arg)
for key, val in kwargs.items():
print(f'{key}={val}')
params = [1, 2, 3]
opts = {'sep': ', ', 'end': '\n'}
display(*params, **opts) |
Demonstrate python pickle module example in 3. Python guide (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) |
Understanding serialize and deserialize objects with pickle in in Python (v8) | import pickle
obj = {'model_weights': [0.1, 0.5, 0.9]}
serialized = pickle.dumps(obj)
recovered = pickle.loads(serialized) |
Code for How do I how to use yield in python in Python (v8) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
When to use How do I chain exceptions using raise from syntax Python (v3) | class AppError(Exception): pass
try:
val = int("invalid")
except ValueError as err:
raise AppError("Failed to parse configuration") from err |
How does Write code for priority queue python. work? (v8) | 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 example of How do I itertools.groupby python example (v4) | import itertools
def group_consecutive(lst):
"""Group consecutive equal elements."""
return [(k, list(v)) for k, v in itertools.groupby(lst)] |
Python Give me an example of python generator send method complete example (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 |
How : ProcessPoolExecutor example is implemented in Python (v7) | 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 snippet: snippet for one liner list transformation python. (v3) | # List comprehension: squares of even numbers
evens_squared = [x**2 for x in range(20) if x % 2 == 0] |
Common use case of What is the best way to group list by key python Python (v3) | import itertools
def group_consecutive(lst):
"""Group consecutive equal elements."""
return [(k, list(v)) for k, v in itertools.groupby(lst)] |
Python: switch statement Python | def http_status(status):
match status:
case 200:
return 'OK'
case 404:
return 'Not Found'
case 500 | 503:
return 'Server Error'
case _:
return 'Unknown' |
How Explain itertools.chain example python with code. is implemented in Python | 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 Raise custom exception tutorial complete example (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 |
When to use Can you show how to read csv file python example Python (v8) | 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) |
Write a function to demonstrate Show me how to structural pattern matching python (v7) | def http_status(status):
match status:
case 200:
return 'OK'
case 404:
return 'Not Found'
case 500 | 503:
return 'Server Error'
case _:
return 'Unknown' |
How does : Spread operator work? (v4) | first, *middle, last = [1, 2, 3, 4, 5]
print(first, last) # 1 5
print(middle) # [2, 3, 4]
# Merge dicts Python 3.9+
a = {'x': 1}
b = {'y': 2}
c = {**a, **b} # {'x': 1, 'y': 2} |
Understanding Write code for python str.format example. in Python (v5) | # 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) |
How Explain and show code to safely write to temporary is implemented in Python (v8) | import tempfile
with tempfile.NamedTemporaryFile(mode='w+', delete=True) as tmp:
tmp.write('temporary data')
tmp.seek(0)
content = tmp.read() |
How What does os.environ python example look like in is implemented in Python (v6) | 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') |
How does Demonstrate user defined exception python in 3. work? (v4) | 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 |
How does Recursively find all files matching glob pattern w work? (v4) | from pathlib import Path
py_files = list(Path('.').rglob('*.py')) |
What is : Singleton design pattern example in Python? (v5) | class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance |
Understanding I want to understand efficient fifo queue python. in Python (v10) | 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) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.