anchor stringlengths 13 118 | positive stringclasses 235
values |
|---|---|
Python 3 What is the best way to with statement custom clas example code (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.... |
Python example of Singleton design pattern example (v6) | class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance |
Explain yield from in python 3 with code. | 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 What does create numpy array python look like in in Python? (v9) | 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 |
Python code showing Code example: pandas read csv python (v7) | 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 3 Code example: trigonometry python example code (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 |
Advanced Code example: how to chain generators using yield Python example (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 |
Python What does type safe generic container python look complete example (v5) | 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() |
Explain How do I bottom up dp python in Python (v2) | 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] |
Advanced Demonstrate lazy list comprehension python in 3. Python example (v4) | # Generator expression - memory efficient
data = range(1_000_000)
total = sum(x**2 for x in data if x % 2 == 0) |
Common use case of Write code for rotating log file python. Python (v8) | 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... |
Python snippet: What does how to call parent class method python l (v7) | 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!' |
Beginner guide to Code example: variable arguments python function Python (v4) | 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) |
What is the best way to how to make python class iterable with indexing? | 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] |
How does Custom addition for objects tutorial work? (v10) | class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f'Vector({self.x}, {self.y})' |
Understanding snippet for python struct module example. in Python (v5) | 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) |
Practical use of What is the best way to map keys to values python in Python (v5) | # Dict comprehension
words = ['hello', 'world', 'python']
word_lengths = {w: len(w) for w in words} |
What is the best way to concurrent async tasks pyt with Python 3 (v6) | import asyncio
async def main():
"""Run tasks concurrently with asyncio.gather."""
results = await asyncio.gather(
fetch('http://api1.com'),
fetch('http://api2.com'),
fetch('http://api3.com'),
)
return results |
How does What does dataclasses.field python example look li work? (v8) | from dataclasses import dataclass, field
@dataclass
class Team:
name: str
members: list = field(default_factory=list)
_id: int = field(default=0, repr=False) |
Python code showing How do I divide and conquer sort python (v8) | 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) |
Python ExceptionGroup example complete example (v3) | # Python 3.11+ ExceptionGroup
try:
raise ExceptionGroup('several errors', [
ValueError('bad value'),
TypeError('bad type'),
])
except* ValueError as eg:
print('ValueErrors:', eg.exceptions)
except* TypeError as eg:
print('TypeErrors:', eg.exceptions) |
Python code showing What is the best way to re.sub python example (v8) | import re
text = 'Hello World Python'
# Replace multiple spaces with single space
cleaned = re.sub(r'\s+', ' ', text.strip()) |
Beginner guide to snippet for itertools.combinations example. Python (v10) | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
Python 3 Parse JSON string tutorial example code (v8) | 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) |
Write a function to demonstrate Can you show python any all example example (v4) | 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 code showing What does priority queue python look like in (v6) | 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) |
Understanding What does partial function application python look in 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 |
Write a function to demonstrate code to use TypedDict for type checked dictionary (v6) | from typing import TypedDict
class UserPayload(TypedDict):
username: str
email: str
is_admin: bool |
Python example of Show me how to python nested function variable in | 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 |
Python code showing What does readable tuple python look like in (v5) | from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # access by name |
Python example of Demonstrate implement for loop support in python c (v8) | 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 |
Practical use of I want to understand python lazy evaluation with y in Python (v5) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
Tutorial on Code example: := operator python 3.8 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] |
Python code showing How do I vectorized operations numpy (v10) | 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 |
Advanced Explain how to use queue in asyncio python with co Python example (v5) | 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... |
generator cleanup on close tutorial with Python 3 (v2) | def resource_gen():
"""Generator with cleanup on close."""
print('Generator started')
try:
while True:
yield
finally:
print('Generator closed - cleanup done') |
Python I want to understand generator.close() python exam complete example (v6) | def resource_gen():
"""Generator with cleanup on close."""
print('Generator started')
try:
while True:
yield
finally:
print('Generator closed - cleanup done') |
What is Write code for handle multiple exceptions at once in Python? (v5) | # 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) |
Explain Explain maintain sorted list python with code. in Python (v7) | import bisect
sorted_list = [1, 3, 5, 7, 9]
bisect.insort(sorted_list, 4) # insert 4 keeping sorted
pos = bisect.bisect_left(sorted_list, 5) # find position of 5 |
When to use snippet for choose r items from list python. Python | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
Beginner guide to Explain parametrized decorator python with code. Python (v9) | 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 ... |
When to use Show me how to pattern matching python 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' |
Explain Explain python thread class example with code. in Python | 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() |
Can you show sort objects multiple criteria python example? | 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'])) |
When to use How do I recursive graph traversal python Python | def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
return visited |
What is Can you show python yield from usage example in Python? (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 |
Python 3 I want to understand python concurrent.futures exa example code (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()... |
Python example of Give me an example of define get endpoint fastapi. (v4) | 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 |
What does argparse python example look like in with Python 3 (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... |
Practical use of Can you show pattern matching python example in 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' |
Tutorial on Code example: hook subclass definition python 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} |
Beginner guide to Lazy evaluation in Python (v8) | def lazy_range(n):
i = 0
while i < n:
yield i
i += 1 |
Practical use of What does parallel processing python look like in in Python (v4) | 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 example of Explain handle multiple exceptions at once 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) |
Practical use of Show me how to python deque example in . in Python (v8) | 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) |
Practical use of What is the best way to flask route example python in Python (v7) | 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}!'}) |
When to use What is the best way to load json file python Python (v9) | 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) |
Write a function to demonstrate Explain run multiple coroutines concurrently pytho (v3) | import asyncio
async def main():
"""Run tasks concurrently with asyncio.gather."""
results = await asyncio.gather(
fetch('http://api1.com'),
fetch('http://api2.com'),
fetch('http://api3.com'),
)
return results |
What is What does sort objects multiple criteria python lo in Python? (v9) | 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: Memoization Python functools | 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 How do I raise from python exception (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 Can you show itertools.islice python example examp is implemented in Python (v4) | import itertools
def take(n, iterable):
"""Return first n items of an iterable as a list."""
return list(itertools.islice(iterable, n)) |
Python snippet: How do I python threading 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() |
Common use case of Show me how to pattern matching python in . Python (v8) | def http_status(status):
match status:
case 200:
return 'OK'
case 404:
return 'Not Found'
case 500 | 503:
return 'Server Error'
case _:
return 'Unknown' |
Common use case of Code example: how to cache function results python 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) |
Demonstrate two-way communication with generator p Python guide (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 |
Explain Demonstrate http get with headers python in 3. in 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() |
Write a function to demonstrate Give me an example of choose r items from list pyt | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
Python example of Validate subclass creation (v7) | 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 snippet: Code example: asyncio.gather python example (v9) | import asyncio
async def main():
"""Run tasks concurrently with asyncio.gather."""
results = await asyncio.gather(
fetch('http://api1.com'),
fetch('http://api2.com'),
fetch('http://api3.com'),
)
return results |
How Code example: python getter setter using property is implemented in Python (v3) | 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... |
Remove duplicates with set comprehension tutorial Python guide (v4) | # Set comprehension: unique first letters
words = ['apple', 'avocado', 'banana', 'blueberry']
first_letters = {w[0] for w in words} |
Code for Parallel processing in Python (v4) | 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) |
How does I want to understand memory efficient class python work? (v6) | 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 |
Write a function to demonstrate : Flask route example | 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}!'}) |
When to use Show me how to consecutive grouping python in . Python (v7) | import itertools
def group_consecutive(lst):
"""Group consecutive equal elements."""
return [(k, list(v)) for k, v in itertools.groupby(lst)] |
Python 3 Show me how to o(log n) search python in . example code | 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 |
Common use case of Config from environment Python (v7) | 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') |
I want to understand decorator factory python. Python guide (v8) | 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 ... |
When to use Nested list comprehension Python | matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [elem for row in matrix for elem in row] |
Beginner guide to Give me an example of python any all example. Python (v10) | 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 |
Write a function to demonstrate snippet for class based decorator python. (v4) | 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 CSV Python tutorial | 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 3 I want to understand benchmark function python. example code (v10) | import cProfile, pstats, timeit
# Quick benchmark
elapsed = timeit.timeit('sum(range(1000))', number=10_000)
print(f'10k runs: {elapsed:.3f}s')
# Full profiling
cProfile.run('my_function()', 'output.prof')
p = pstats.Stats('output.prof').sort_stats('cumulative')
p.print_stats(10) |
When to use Explain dictionary from two lists python with code Python (v10) | # Dict comprehension
words = ['hello', 'world', 'python']
word_lengths = {w: len(w) for w in words} |
Code for Explain how does yield work in python with code. in Python (v8) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
Understanding How do I string manipulation python in Python (v3) | 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)) |
: __get__ __set__ __delete__ Python guide (v7) | class Positive:
"""Descriptor that enforces positive values."""
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
return getattr(obj, f'_{self.name}', None)
def __set__(self, obj, value):
if value <= 0:
raise ValueError(f'{s... |
Python example of Write code for logical or/and over list python. (v9) | 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 |
How does How do I how to use nonlocal in python work? (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 |
Python snippet: Explain pytest fixture example with code. (v4) | 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 |
Explain Pattern matching tutorial in Python (v8) | def http_status(status):
match status:
case 200:
return 'OK'
case 404:
return 'Not Found'
case 500 | 503:
return 'Server Error'
case _:
return 'Unknown' |
Example of how to breadth first search traversal o with Python 3 (v7) | from collections import deque
def bfs(graph, root):
visited = {root}
q = deque([root])
order = []
while q:
node = q.popleft()
order.append(node)
for neighbor in graph.get(node, []):
if neighbor not in visited:
visited.add(neighbor)
q.a... |
Write a function to demonstrate snippet for factory method python example. (v5) | 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() |
Code example: group by pandas python Python guide (v4) | 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 3 How do I parse csv with header python example code (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) |
Practical use of Show me how to generator based context manager pyt in Python (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') |
Best practice to limit concurrent async tasks using asyncio.Semaphore with Python | import asyncio
async def bounded_request(sem, url):
async with sem:
await asyncio.sleep(0.5)
return f"Fetched {url}"
async def main():
sem = asyncio.Semaphore(5)
tasks = [bounded_request(sem, f"http://site.com/{i}") for i in range(20)]
return await asyncio.gather(*tasks) |
Understanding What does named constants python enum look like in in Python (v6) | 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) |
Understanding What is the best way to resource management python in Python (v10) | 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.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.