anchor stringlengths 13 118 | positive stringclasses 235
values |
|---|---|
Common use case of How do I basemodel pydantic python Python (v2) | 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... |
Python Code example: collections.counter tutorial complete example (v9) | from collections import Counter
words = 'the quick brown fox jumps over the lazy dog'.split()
counts = Counter(words)
print(counts.most_common(3)) |
Understanding Explain singleton design pattern python example wi in Python (v7) | class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance |
What is the best way to yield statement python tut with Python 3 | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
Python 3 Write code for **kwargs python example. example code (v8) | 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) |
Code for snippet for python exceptiongroup 3.11. in Python (v9) | # 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 : Read text file is implemented in 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!') |
Give me an example of split join strip python stri with Python 3 (v2) | 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)) |
Python snippet: How do I resume a function from where it left pyth (v7) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
Code for Explain regex replace python with code. in Python (v5) | 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 custom sequence python class Python (v10) | 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 I want to understand cache expensive function call is implemented in Python (v10) | 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 Write code for structural subtyping python. is implemented in Python (v8) | 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 |
Code for What is the best way to functional programming pyt in Python (v8) | 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) |
Write a function to demonstrate : Parse JSON string (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) |
Code for snippet for how to send values into a generator py in Python (v9) | def accumulator():
"""Generator that receives values via send() and accumulates."""
total = 0
while True:
value = yield total
if value is None:
break
total += value |
Tutorial on Show me how to python coroutine send value in . Python (v7) | def accumulator():
"""Generator that receives values via send() and accumulates."""
total = 0
while True:
value = yield total
if value is None:
break
total += value |
Understanding What is the best way to memory efficient file read 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')) |
snippet for fibonacci with dynamic programming pyt with Python 3 (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] |
Explain map keys to values python one liner with code. | # Dict comprehension
words = ['hello', 'world', 'python']
word_lengths = {w: len(w) for w in words} |
Beginner guide to Can you show trigonometry python example Python (v4) | 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 |
When to use Give me an example of python type annotation examp Python (v8) | 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] |
Python example of Show me how to all subsets of size r python in . | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
Practical use of Demonstrate find n smallest python in 3. in Python | 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) |
Demonstrate variance python statistics in 3. Python guide (v5) | 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 |
Write a function to demonstrate Demonstrate add behaviour to function without modi (v7) | 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 |
What is Explain try except else finally python with code. in 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 does Demonstrate @contextmanager decorator python in 3 work? (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') |
How : Singleton pattern is implemented in Python (v8) | class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance |
Python 3 Give me an example of python recursive sort exampl example code (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) |
use pathlib tutorial Python guide (v4) | 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') |
Give me an example of generator.close() python example. | def resource_gen():
"""Generator with cleanup on close."""
print('Generator started')
try:
while True:
yield
finally:
print('Generator closed - cleanup done') |
Explain What is the best way to python dataclass example in Python (v10) | 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 generator.throw() method python. with Python 3 (v4) | def safe_gen():
"""Generator that handles injected exceptions."""
try:
while True:
yield
except ValueError as e:
print(f'Caught: {e}')
yield 'recovered' |
Code for Code example: implement merge sort python in Python | 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(... |
Write a function to demonstrate Give me an example of control class creation pytho (v3) | class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Config(metaclass=SingletonMeta):
def __init__(self):
self.debug = False |
Understanding Show me how to python walrus operator example in . in Python (v8) | # 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] |
Code for snippet for loop with index python. in Python (v7) | 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}') |
Can you show implement trie python example with Python 3 | 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 What is the best way to python logging to file exa Python (v5) | 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 3 Explain group items by key python with code. example code (v8) | 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) |
Common use case of What is the best way to thread safe counter python Python (v8) | 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 |
Advanced Give me an example of how to pass data into a paus Python example (v8) | def accumulator():
"""Generator that receives values via send() and accumulates."""
total = 0
while True:
value = yield total
if value is None:
break
total += value |
Python code to read CSV into dictionary rows using csv.DictReader | import csv
def read_csv(path):
with open(path, newline='', encoding='utf-8') as f:
return list(csv.DictReader(f)) |
Write a function to demonstrate Give me an example of custom iterator class python | 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 |
When to use Demonstrate heapq.heappush python tutorial in 3. Python (v10) | 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) |
Beginner guide to What is the best way to function that remembers ou Python (v3) | def make_counter(start=0):
"""Closure that maintains a counter."""
count = [start]
def increment(by=1):
count[0] += by
return count[0]
return increment |
Write a function to demonstrate Write code for multiple inheritance mixin python. (v6) | 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 |
Python code showing Explain file system operations pathlib python with (v2) | 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') |
Common use case of What is the best way to how to create custom excep Python (v3) | 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 snippet: read huge files line by line lazily using generato (v7) | def read_large_file(file_path):
"""Read file line by line without buffering entire file in RAM."""
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
yield line.strip() |
What is __iter__ and __next__ tutorial in Python? (v3) | 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 |
snippet for generator based context manager python Python guide (v10) | 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') |
How does Show me how to raise custom exception python in . work? (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 |
Tutorial on Show me how to abc python example in . Python (v8) | 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 snippet for reusable test setup python pytest. | 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 |
Practical use of Explain python string representation of object wit in Python (v6) | class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f'Point({self.x!r}, {self.y!r})'
def __str__(self):
return f'({self.x}, {self.y})' |
I want to understand data validation python pydant with Python 3 (v9) | 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... |
Explain requests post example in Python (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()) |
How does What does avoid circular reference python look lik work? (v6) | 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 |
Code for Give me an example of mutable default in dataclass in Python | from dataclasses import dataclass, field
@dataclass
class Team:
name: str
members: list = field(default_factory=list)
_id: int = field(default=0, repr=False) |
Common use case of Can you show map keys to values python one liner e Python (v2) | # Dict comprehension
words = ['hello', 'world', 'python']
word_lengths = {w: len(w) for w in words} |
Explain Explain python dict comprehension example with cod in Python | # Dict comprehension
words = ['hello', 'world', 'python']
word_lengths = {w: len(w) for w in words} |
Beginner guide to Demonstrate make attribute read only python in 3. 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... |
Give me an example of remove duplicates with set comprehension. | # Set comprehension: unique first letters
words = ['apple', 'avocado', 'banana', 'blueberry']
first_letters = {w[0] for w in words} |
When to use What is the best way to generic type hint python Python (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() |
Can you show pytest fixture python example? | 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 code showing How do I generator.throw() method python (v2) | def safe_gen():
"""Generator that handles injected exceptions."""
try:
while True:
yield
except ValueError as e:
print(f'Caught: {e}')
yield 'recovered' |
Python snippet for inject error into python generator. complete example (v8) | def safe_gen():
"""Generator that handles injected exceptions."""
try:
while True:
yield
except ValueError as e:
print(f'Caught: {e}')
yield 'recovered' |
Understanding Demonstrate super() python example in 3. in Python (v2) | 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!' |
Practical use of itemgetter attrgetter in Python (v5) | 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 |
Practical use of snippet for parametrize pytest. in Python (v4) | import pytest
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
@pytest.mark.parametrize('a,b,expected', [(1,2,3),(0,0,0),(-1,1,0)])
def test_add_parametric(a, b, expected):
assert add(a, b) == expected |
Python snippet for class based decorator python. | 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) |
Explain take first n items from generator python with code. | import itertools
def take(n, iterable):
"""Return first n items of an iterable as a list."""
return list(itertools.islice(iterable, n)) |
Explain I want to understand create directory python pathl in Python (v5) | 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') |
Practical use of functools.cache example tutorial in Python (v6) | from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
"""Compute nth Fibonacci number using memoization."""
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2) |
Practical use of I want to understand python generator expression e in Python (v5) | # Generator expression - memory efficient
data = range(1_000_000)
total = sum(x**2 for x in data if x % 2 == 0) |
When to use Can you show python path object example example Python (v3) | 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') |
Explain Demonstrate generator.throw() method python in 3. in Python (v10) | def safe_gen():
"""Generator that handles injected exceptions."""
try:
while True:
yield
except ValueError as e:
print(f'Caught: {e}')
yield 'recovered' |
Tutorial on Show me how to os.environ python example in . Python (v4) | 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') |
Show me how to asyncio.gather python example in . Python guide (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 |
Code for Write code for square root python. in Python (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 How do I force subclass to implement method python Python example (v6) | 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... |
Beginner guide to Code example: fibonacci with dynamic programming p 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] |
Beginner guide to How do I use Literal type to restrict parameter to Python (v10) | from typing import Literal
def set_mode(mode: Literal['read', 'write', 'append']):
print(f"Opening in {mode} mode") |
Understanding Code example: collections.defaultdict tutorial in Python (v8) | from collections import defaultdict
# Group words by first letter
words = ['apple', 'avocado', 'banana', 'blueberry', 'cherry']
groups = defaultdict(list)
for word in words:
groups[word[0]].append(word) |
Tutorial on read and write JSON tutorial Python (v10) | 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) |
Python Union type hint tutorial complete example (v7) | from typing import Union
def to_int(val: Union[str, float, int]) -> int:
"""Convert string, float or int to int."""
return int(val) |
Python snippet: Explain and show code to create a closure that mai (v7) | def make_counter(start=0):
count = start
def step():
nonlocal count
count += 1
return count
return step |
What is the best way to python counter example? | from collections import Counter
words = 'the quick brown fox jumps over the lazy dog'.split()
counts = Counter(words)
print(counts.most_common(3)) |
Code for What does reduce python object memory look like in in Python (v8) | 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 |
Advanced Demonstrate speed up recursive function python cac Python example (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) |
Can you show close a running generator python example? | def resource_gen():
"""Generator with cleanup on close."""
print('Generator started')
try:
while True:
yield
finally:
print('Generator closed - cleanup done') |
Write a function to demonstrate Code example: how to create custom exception pytho (v5) | 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 example of How do I implement singleton pattern with a class (v7) | def singleton(cls):
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance |
Explain What does how to mock in python tests look like in in Python | from unittest.mock import patch, MagicMock
def get_user(user_id):
import requests
return requests.get(f'/users/{user_id}').json()
def test_get_user():
with patch('requests.get') as mock_get:
mock_get.return_value.json.return_value = {'id': 1, 'name': 'Alice'}
result = get_user(1)
a... |
Python defaultdict example 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) |
Python snippet: Give me an example of http get with headers python (v7) | import requests
response = requests.get(
'https://api.example.com/data',
headers={'Authorization': 'Bearer token'},
timeout=10
)
response.raise_for_status()
data = response.json() |
Explain I want to understand python readline example. 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')) |
Python snippet: slice an iterator (v8) | import itertools
def take(n, iterable):
"""Return first n items of an iterable as a list."""
return list(itertools.islice(iterable, n)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.