anchor stringlengths 13 118 | positive stringclasses 235
values |
|---|---|
Python example of Can you show callable class python example (v7) | class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
double = Multiplier(2)
print(double(5)) # 10 |
Beginner guide to Demonstrate how to slice an iterator python in 3. Python (v8) | import itertools
def take(n, iterable):
"""Return first n items of an iterable as a list."""
return list(itertools.islice(iterable, n)) |
Can you show try except else finally 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') |
Beginner guide to Write code for group items by key python. Python | from collections import defaultdict
# Group words by first letter
words = ['apple', 'avocado', 'banana', 'blueberry', 'cherry']
groups = defaultdict(list)
for word in words:
groups[word[0]].append(word) |
Advanced Show me how to send json data http python in . Python example (v9) | 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()) |
I want to understand fastapi route 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 snippet: Explain choose r items from list python with code. (v7) | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
Give me an example of bitwise flags python. | 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 |
Python snippet: What is the best way to all subsets of size r pyth | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
Explain http get with headers python with code. | import requests
response = requests.get(
'https://api.example.com/data',
headers={'Authorization': 'Bearer token'},
timeout=10
)
response.raise_for_status()
data = response.json() |
Python snippet: Explain __iter__ and __next__ python with code. (v2) | 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 |
Python 3 : Interface in using Protocol example code (v4) | 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 |
When to use : HTTP GET with headers Python (v3) | import requests
response = requests.get(
'https://api.example.com/data',
headers={'Authorization': 'Bearer token'},
timeout=10
)
response.raise_for_status()
data = response.json() |
Python 3 Explain factory design pattern python with code. example code (v4) | 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 snippet: What does generate random number python look like (v2) | import random
print(random.randint(1, 100)) # integer [1, 100]
print(random.random()) # float [0, 1)
print(random.choice(['a','b','c'])) # pick one
lst = list(range(10))
random.shuffle(lst) # in-place shuffle
sample = random.sample(lst, 3) # 3 unique picks |
Python snippet: Demonstrate itertools.product python example in 3 (v6) | import itertools
def cartesian_product(a, b):
"""Compute Cartesian product of two iterables."""
return list(itertools.product(a, b)) |
What is Can you show how to create custom exception python in Python? (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 |
Python Demonstrate double ended queue python in 3. complete example | 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 DictReader csv in Python (v2) | 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 How do I python requests post example 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()) |
Beginner guide to Create pandas DataFrame 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 |
When to use Demonstrate pandas read csv python in 3. Python (v2) | 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 |
Common use case of pickle module example 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) |
When to use lru_cache decorator example 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) |
How do I try except else finally python? | 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') |
When to use Explain load json file python with code. Python (v5) | import json
# Deserialize
with open('data.json') as f:
data = json.load(f)
# Serialize
with open('output.json', 'w') as f:
json.dump(data, f, indent=2)
# String operations
text = json.dumps({'key': 'value'})
obj = json.loads(text) |
How do I implement comparison operators __lt__ __g with Python 3 (v10) | from functools import total_ordering
@total_ordering
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def __eq__(self, other):
return self.grade == other.grade
def __lt__(self, other):
return self.grade < other.grade |
Show me how to file system operations pathlib pyth Python guide (v6) | 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 does Explain and show code to read and write JSON file work? (v7) | import json
data = {'name': 'Alice', 'roles': ['admin', 'user']}
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
with open('data.json', 'r', encoding='utf-8') as f:
loaded = json.load(f) |
Explain : Extended unpacking 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} |
Explain Show me how to object creation strategy python in in Python (v9) | 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() |
Common use case of What is the best way to named constants python enu Python (v5) | 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 example of : Shuffle list (v2) | 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 |
Explain union type hint python with code. | from typing import Union
def to_int(val: Union[str, float, int]) -> int:
"""Convert string, float or int to int."""
return int(val) |
When to use code to generate pseudo random numbers and sample Python (v3) | import random
def lottery(candidates, k=3):
random.seed(42)
chosen = random.sample(candidates, k)
random.shuffle(candidates)
return chosen |
What is Best practice to recursively find all files matchi in Python? (v3) | from pathlib import Path
py_files = list(Path('.').rglob('*.py')) |
Explain Demonstrate run function in separate thread python in Python (v5) | 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 code showing Can you show raise from python exception example (v10) | 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 Write code for python map filter reduce example. complete example (v5) | 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) |
Code for I want to understand custom iterator class 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 |
Python example of unittest.mock patch tutorial (v6) | 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 3 Ensure single instance example code (v5) | class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance |
Beginner guide to Give me an example of setup and teardown pytest. Python (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 |
How snippet for unpack list into variables python. is implemented 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} |
Explain How do I python math.floor ceil round in Python (v8) | 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 Can you show default value dict python example work? (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) |
Python example of How do I build dictionary with comprehension (v9) | # Dict comprehension
words = ['hello', 'world', 'python']
word_lengths = {w: len(w) for w in words} |
Python snippet: Give me an example of group by pandas python. (v8) | 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 |
What is Code example: process large file python in Python? (v10) | # Memory-efficient line-by-line reading
with open('large_file.txt', encoding='utf-8') as f:
for line in f:
process(line.rstrip('\n')) |
Beginner guide to Write code for python exceptiongroup 3.11. Python | # 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) |
What is Duck typing with type hints tutorial in Python? (v3) | from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
def render(obj: Drawable) -> None:
obj.draw()
# Any class with draw() satisfies Drawable without inheritance |
Write a function to demonstrate What is the best way to unpack list into variables (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} |
Tutorial on : File handling 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!') |
Code example: callback registration python with Python 3 (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) |
Understanding : str.format example in Python (v9) | # 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) |
Python code showing I want to understand find slow code python. (v8) | 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) |
Python How do I super() in inheritance python complete example (v4) | 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 3 Take first N items from generator tutorial example code (v3) | import itertools
def take(n, iterable):
"""Return first n items of an iterable as a list."""
return list(itertools.islice(iterable, n)) |
Iterate two lists simultaneously Python tutorial | 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}') |
What is I want to understand write tests with pytest. in Python? (v9) | 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 |
Practical use of Can you show validate attribute with descriptor py in Python | 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... |
How does Explain how to make a class a decorator python wit work? (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) |
Common use case of What does how to pass data into a paused generator Python (v2) | 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 Setup and teardown pytest Python (v7) | 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 |
Give me an example of convert int to bytes python Python guide (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) |
Python snippet: Code example: python chain iterators together (v9) | import itertools
def chain_all(*iterables):
"""Chain multiple iterables into one using itertools."""
return list(itertools.chain(*iterables))
# Usage: chain_all([1,2], [3,4], [5]) -> [1,2,3,4,5] |
Write a function to demonstrate What does patch function python unittest look like (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... |
What is implement operator overloading for addition using in Python? | class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
if isinstance(other, Vector):
return Vector(self.x + other.x, self.y + other.y)
return NotImplemented |
Tutorial on How do I data validation python pydantic Python (v8) | from pydantic import BaseModel, Field, validator
from typing import Optional
class User(BaseModel):
name: str
email: str
age: int = Field(gt=0, le=150)
bio: Optional[str] = None
@validator('email')
def email_must_have_at(cls, v):
if '@' not in v:
raise ValueError('invalid e... |
Code for I want to understand how to add type hints in pyth in Python (v2) | 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] |
I want to understand flask route example 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}!'}) |
Python How do I matrix to flat list python complete example (v2) | matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [elem for row in matrix for elem in row] |
Python snippet: What is the best way to what is a decorator in pyt | 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 Explain copy nested object python with code. Python (v2) | 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 |
Explain Explain check all elements satisfy condition pytho in Python (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 |
Common use case of functools.cache example tutorial Python (v9) | 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 unittest example | 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() |
What is snippet for filter list with comprehension python. in Python? (v4) | # List comprehension: squares of even numbers
evens_squared = [x**2 for x in range(20) if x % 2 == 0] |
How does Show me how to pickle dump and load python in . work? (v2) | 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) |
Tutorial on Code example: read text file python Python (v2) | # 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!') |
Python example of Show me how to functools.reduce python in . (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) |
Explain csv module example in Python (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) |
What is : Resume a function from where it left in Python? (v9) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
Common use case of Give me an example of how to use yield in python. Python (v2) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
Python code showing Write code for raise from python exception. (v9) | 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') |
Understanding I want to understand standard deviation python. in Python (v7) | import statistics as stats
data = [2, 4, 4, 4, 5, 5, 7, 9]
print(stats.mean(data)) # 5.0
print(stats.median(data)) # 4.5
print(stats.mode(data)) # 4
print(stats.stdev(data)) # 2.0 |
Beginner guide to What is the best way to save and load python objec Python (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 Write code for python csv module example. Python (v6) | 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) |
Understanding : Parallel processing 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) |
Common use case of : ExceptionGroup example 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) |
Beginner guide to : pytest fixture Python (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 example of Show me how to dataclass field with default factor (v6) | 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 What is the best way to python logging module exam 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) |
How : exception hierarchy example is implemented in Python (v7) | 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') |
Demonstrate bisect.insort python tutorial in 3. with Python 3 (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 |
Write a function to demonstrate Show me how to generic function python typing in . (v10) | 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() |
Advanced How do I choose r items from list python Python example (v5) | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
Python snippet: Code example: filter list python (v5) | 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) |
Code for What is the best way to sort by multiple keys pyth in Python (v5) | 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 3 Explain rotating log file python with code. example code (v10) | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.