anchor
stringlengths
13
118
positive
stringclasses
235 values
Python code showing I want to understand immutable dataclass python. (v6)
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
Python example of Write code for fastapi tutorial python. (v3)
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
Common use case of Combine enum values Python (v7)
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 code showing Explain python dict comprehension example with cod (v2)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
When to use snippet for python dataclass list default value. Python
from dataclasses import dataclass, field @dataclass class Team: name: str members: list = field(default_factory=list) _id: int = field(default=0, repr=False)
Explain Show me how to bisect.insort python tutorial in . in Python (v4)
import bisect sorted_list = [1, 3, 5, 7, 9] bisect.insort(sorted_list, 4) # insert 4 keeping sorted pos = bisect.bisect_left(sorted_list, 5) # find position of 5
Python I want to understand python enum example. complete example (v3)
from enum import Enum, auto class Color(Enum): RED = auto() GREEN = auto() BLUE = auto() print(Color.RED) # Color.RED print(Color.RED.value) # 1 for color in Color: print(color.name)
How Give me an example of filter list with comprehensi is implemented in Python (v4)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
Code for How do I 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)
Beginner guide to Code example: patch function python unittest Python (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...
Tutorial on I want to understand generator.close() python exam Python (v4)
def resource_gen(): """Generator with cleanup on close.""" print('Generator started') try: while True: yield finally: print('Generator closed - cleanup done')
Python : Generator function that pauses execution complete example (v8)
def count_up(n): """Generator that yields numbers 0 to n-1.""" for i in range(n): yield i
Python 3 Write code for unpack list into variables python. example code (v8)
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 code to implement __str__ and __repr__ for custom in Python (v5)
class User: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f"User(name={self.name!r}, age={self.age!r})" def __str__(self): return f"{self.name} ({self.age} years old)"
Unpack list into variables Python tutorial
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 Can you show file system operations pathlib python in Python (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')
Python code to implement singleton pattern or customize o complete example (v10)
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance
Understanding snippet for python requests post example. in Python (v4)
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())
When to use Give me an example of rotate list python deque. 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)
Explain : Descriptor protocol in Python (v9)
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...
f string with expressions Python tutorial
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 : generator.close() example in Python? (v4)
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 What does python functools.partial example look li (v7)
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
Practical use of Demonstrate file system operations pathlib python 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')
Python example of Write code for pytest fixture python. (v8)
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
Understanding : Iterate two lists simultaneously in Python (v10)
names = ['Alice', 'Bob', 'Carol'] scores = [95, 87, 92] # zip: pair elements for name, score in zip(names, scores): print(f'{name}: {score}') # enumerate: add index for i, name in enumerate(names, start=1): print(f'{i}. {name}')
Python example of Example of how to define Pydantic BaseModel with f (v9)
from pydantic import BaseModel, Field, field_validator class User(BaseModel): id: int email: str age: int = Field(ge=0, le=120) @field_validator('email') def validate_email(cls, v): if '@' not in v: raise ValueError('Invalid email') return v
Python snippet: Give me an example of re.sub python example. (v2)
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
Write code for python zip example. with Python 3 (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}')
How snippet for structural pattern matching classes py is implemented in Python (v9)
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...
When to use : @property class example Python
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...
Code for Show me how to speed up recursive function python in Python (v5)
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 example of Code example: observer pattern python (v2)
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)
Python code showing How do I implement indexing in python class (v2)
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 snippet for bfs algorithm python. is implemented in Python (v8)
from collections import deque def bfs(graph, start): visited = {start} queue = deque([start]) order = [] while queue: node = queue.popleft() order.append(node) for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) ...
Practical use of What is the best way to depth first search python in Python (v6)
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
How does What does python string representation of object l work? (v8)
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})'
What does destructuring in python match look like in Python?
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...
Understanding How do I concatenate iterables without copying in Python (v6)
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]
Beginner guide to re.match groups Python (v7)
import re pattern = re.compile(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})') m = pattern.search('Date: 2024-03-15') if m: print(m.group('year'), m.group('month'), m.group('day'))
What is What does object overhead python 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
Python code showing mock in tests tutorial (v4)
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...
Explain how to create a context manager python with code.
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....
How does snippet for write to file python. work? (v6)
# 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!')
How Show me how to pattern match object python in . is implemented in Python (v10)
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...
Python snippet for named expression python walrus.
# 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]
I want to understand binary search algorithm pytho with Python 3 (v7)
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
Can you show simple rest api flask python 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}!'})
Python 3 What does weakvaluedictionary python look like in example code (v4)
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
Python Write code for write csv python. complete example (v9)
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)
Beginner guide to Demonstrate binary search python in 3. Python (v9)
import bisect sorted_list = [1, 3, 5, 7, 9] bisect.insort(sorted_list, 4) # insert 4 keeping sorted pos = bisect.bisect_left(sorted_list, 5) # find position of 5
Python code showing Write code for read text file python. (v4)
# 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!')
Beginner guide to Write code for read file line by line python. Python (v6)
# Memory-efficient line-by-line reading with open('large_file.txt', encoding='utf-8') as f: for line in f: process(line.rstrip('\n'))
Tabulation approach Python tutorial
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]
Show me how to implement merge sort python in . with Python 3 (v5)
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(...
How to make class iterable 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
Python code showing Write code for close a running generator python. (v4)
def resource_gen(): """Generator with cleanup on close.""" print('Generator started') try: while True: yield finally: print('Generator closed - cleanup done')
Give me an example of pre-fill function arguments Python guide (v3)
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
Python snippet: What does dfs algorithm python look like in (v6)
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
How : requests library example is implemented in Python (v9)
import requests response = requests.get( 'https://api.example.com/data', headers={'Authorization': 'Bearer token'}, timeout=10 ) response.raise_for_status() data = response.json()
: Accept multiple types function with Python 3 (v8)
from typing import Union def to_int(val: Union[str, float, int]) -> int: """Convert string, float or int to int.""" return int(val)
Code example: transform list with map python Python guide (v7)
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 example: how to make a class a decorator pyth Python guide
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 What is the best way to python any all example in Python (v3)
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 3 How do I plugin registration python __init_subclas example code (v5)
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}
Common use case of argparse example Python (v2)
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...
How do I min heap 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)
Beginner guide to I want to understand group items by key python. Python (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)
How do I validate input python pydantic Python guide (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 example of How do I how to use threads in python (v4)
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 How do I itertools.islice python example complete example (v2)
import itertools def take(n, iterable): """Return first n items of an iterable as a list.""" return list(itertools.islice(iterable, n))
Common use case of snippet for interface python abc module. Python (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...
re.match groups with Python 3 (v10)
import re pattern = re.compile(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})') m = pattern.search('Date: 2024-03-15') if m: print(m.group('year'), m.group('month'), m.group('day'))
Python example of Write code for convert dict to json python.
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)
Explain Find slow code tutorial in Python (v3)
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)
Give me an example of simple context manager using generator.
from contextlib import contextmanager @contextmanager def timer(label=''): """Context manager that times a block.""" import time start = time.perf_counter() try: yield finally: elapsed = time.perf_counter() - start print(f'{label}: {elapsed:.4f}s')
Python 3 Demonstrate yield from in python 3 in 3. example code (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
How does I want to understand named capture groups python r work?
import re pattern = re.compile(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})') m = pattern.search('Date: 2024-03-15') if m: print(m.group('year'), m.group('month'), m.group('day'))
Advanced use pathlib tutorial Python example (v10)
from pathlib import Path base = Path.home() / 'projects' / 'myapp' base.mkdir(parents=True, exist_ok=True) # List all .py files recursively py_files = list(base.rglob('*.py')) # Read / write (base / 'config.txt').write_text('setting=value')
How Code example: random choice python is implemented in Python (v5)
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 for add behaviour to function without modifying it python.
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
How I want to understand old style string formatting p is implemented in Python (v2)
# 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 example of Code example: re.match groups python (v3)
import re pattern = re.compile(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})') m = pattern.search('Date: 2024-03-15') if m: print(m.group('year'), m.group('month'), m.group('day'))
Tutorial on How does yield work in Python
def count_up(n): """Generator that yields numbers 0 to n-1.""" for i in range(n): yield i
Python code showing Demonstrate one liner list transformation python i (v6)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
How to read and write files 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!')
Python snippet: What is the best way to write csv 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)
Python 3 Demonstrate auto generate __init__ python in 3. example code (v2)
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
How I want to understand add behaviour with mixin pyth is implemented in Python
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 snippet: add type hints in (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]
Write a function to demonstrate I want to understand extend exception class python (v2)
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 Create context manager with yield tutorial complete example (v2)
from contextlib import contextmanager @contextmanager def timer(label=''): """Context manager that times a block.""" import time start = time.perf_counter() try: yield finally: elapsed = time.perf_counter() - start print(f'{label}: {elapsed:.4f}s')
Python 3 What does create context manager with yield python example code (v6)
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')
Explain Best practice to memoize function output with func in Python (v6)
from functools import lru_cache @lru_cache(maxsize=128) def slow_fibonacci(n): if n < 2: return n return slow_fibonacci(n - 1) + slow_fibonacci(n - 2)
What is code to format and inspect exception stack trace w in Python? (v2)
import traceback try: 1 / 0 except ZeroDivisionError: error_msg = traceback.format_exc() print(f"Captured traceback:\n{error_msg}")
Write code for threadpoolexecutor python. with Python 3 (v9)
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()...
Tutorial on Demonstrate python coroutine example in 3. Python (v4)
import asyncio async def fetch_data(url: str) -> str: """Simulate async HTTP fetch.""" await asyncio.sleep(1) # simulate network delay return f'Data from {url}'
Can you show notify subscribers python example with Python 3
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)
How does Best practice to configure logging with rotating f work? (v4)
import logging from logging.handlers import RotatingFileHandler logger = logging.getLogger('app') logger.setLevel(logging.INFO) handler = RotatingFileHandler('app.log', maxBytes=1_000_000, backupCount=3) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.a...
Python code showing Code example: exceptiongroup python example (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)