anchor
stringlengths
13
118
positive
stringclasses
235 values
Python: Variance Python statistics
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 : Rotating log file (v6)
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...
How do I take first n items from generator python Python guide (v4)
import itertools def take(n, iterable): """Return first n items of an iterable as a list.""" return list(itertools.islice(iterable, n))
Advanced pass arguments to a decorator Python example (v6)
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 ...
Explain Give me an example of __iter__ and __next__ python in Python (v9)
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
Beginner guide to How do I python threading.lock example Python (v9)
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
Validate attribute with descriptor Python guide (v2)
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...
Common use case of What is the best way to build dictionary with comp Python (v3)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
Python Explain and show code to implement custom context complete example (v8)
class Timer: import time def __enter__(self): self.start = self.time.perf_counter() return self def __exit__(self, exc_type, exc_val, exc_tb): self.elapsed = self.time.perf_counter() - self.start print(f"Elapsed time: {self.elapsed:.4f}s") return False
Python code showing Can you show operator.attrgetter sort python examp (v8)
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']))
Practical use of Explain and show code to breadth first search trav in Python (v4)
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 Explain python __slots__ vs __dict__ with code. (v10)
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 snippet: Explain and show code to wait for thread signals u (v2)
import threading event = threading.Event() def worker(): print("Waiting for start signal...") event.wait() print("Signal received, working!") t = threading.Thread(target=worker) t.start() event.set()
Python snippet: Code example: logical or/and over list python (v2)
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
Advanced What does python math.floor ceil round look like i Python example (v5)
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 What is the best way to python nested loop replace Python (v9)
import itertools def cartesian_product(a, b): """Compute Cartesian product of two iterables.""" return list(itertools.product(a, b))
I want to understand functools.reduce python.
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)
I want to understand python sort lambda example. Python guide (v9)
people = [('Alice', 30), ('Bob', 25), ('Carol', 35)] # Sort by age ascending by_age = sorted(people, key=lambda p: p[1]) # Sort by name descending by_name_desc = sorted(people, key=lambda p: p[0], reverse=True)
Write a function to demonstrate logging to file example tutorial (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...
Python code showing What does python higher order function decorator l (v5)
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
Give me an example of copy nested object python. with Python 3 (v3)
import copy original = [[1, 2, 3], [4, 5, 6]] shallow = copy.copy(original) # nested lists still shared deep = copy.deepcopy(original) # fully independent copy deep[0][0] = 99 print(original[0][0]) # still 1
Customize object boolean evaluation using __bool__ with Python 3 (v2)
class Account: def __init__(self, balance): self.balance = balance def __bool__(self): return self.balance > 0
Python Explain profile python code performance with code. complete example (v4)
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)
Beginner guide to What is the best way to collections.ordereddict tu Python (v8)
from collections import OrderedDict od = OrderedDict() od['a'] = 1 od['b'] = 2 od.move_to_end('a') # move 'a' to end
What is snippet for itertools.islice python example. in Python? (v9)
import itertools def take(n, iterable): """Return first n items of an iterable as a list.""" return list(itertools.islice(iterable, n))
How does What does python protocol typing example look like work? (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
Tutorial on Assert equal unittest Python (v3)
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()
Python code showing snippet for how to use regex in python. (v10)
import re # Find all email addresses text = 'Contact alice@example.com or bob@test.org' emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', text)
Code for What does factory design pattern python look like in Python (v2)
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 for operator.attrgetter sort tutorial in Python
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 example of I want to understand priority queue python. (v9)
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)
Explain I want to understand bisect.insort python tutorial in Python
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
Code for Ignore specific exception in Python (v4)
from contextlib import suppress with suppress(FileNotFoundError): os.remove('nonexistent.txt') # no error raised
Write a function to demonstrate Format and inspect exception stack trace with trac (v9)
import traceback try: 1 / 0 except ZeroDivisionError: error_msg = traceback.format_exc() print(f"Captured traceback:\n{error_msg}")
Delegating generator with Python 3 (v8)
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
Code example: group items by key 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)
When to use Spread operator Python (v4)
first, *middle, last = [1, 2, 3, 4, 5] print(first, last) # 1 5 print(middle) # [2, 3, 4] # Merge dicts Python 3.9+ a = {'x': 1} b = {'y': 2} c = {**a, **b} # {'x': 1, 'y': 2}
Common use case of I want to understand python exceptiongroup 3.11. Python (v8)
# 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)
Write a function to demonstrate Explain when to use classmethod python with code. (v8)
class Date: """Date class demonstrating classmethod and staticmethod.""" def __init__(self, year, month, day): self.year, self.month, self.day = year, month, day @classmethod def from_string(cls, s): """Alternative constructor from 'YYYY-MM-DD' string.""" year, month, day = map(...
What does python csv module example look like in with Python 3 (v5)
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)
Advanced Give me an example of enumeration class python. Python example (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)
How does Code example: map keys to values python one liner work? (v2)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
Give me an example of binary file format python. with Python 3 (v8)
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)
What is Give me an example of simple pytest test python. in 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
Beginner guide to Demonstrate pytest fixture example in 3. Python (v10)
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
Common use case of readline example 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'))
Common use case of What does patch function python unittest look like Python (v9)
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 Can you show standard deviation python example in Python? (v3)
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
Code for What is the best way to parse json string python in Python (v2)
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)
Advanced Give me an example of function that remembers oute Python example (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
Python example of Explain and show code to make class instance calla
class Adder: def __init__(self, value): self.value = value def __call__(self, x): return self.value + x add_five = Adder(5) result = add_five(10) # 15
Python snippet: How do I stable sort python recursive (v3)
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(...
Beginner guide to Give me an example of python test class. Python (v9)
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 the best way to *args **kwargs python?
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 python weakref example with code.
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 python __init_subclass__ example. complete example
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}
How : Remove duplicates with set comprehension is implemented in Python (v2)
# Set comprehension: unique first letters words = ['apple', 'avocado', 'banana', 'blueberry'] first_letters = {w[0] for w in words}
When to use Code example: insert into sorted list python Python (v3)
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 example of What does transform list with map python look like (v3)
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)
Advanced Write code for python zip example. Python example (v5)
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 Stateful decorator using class tutorial is implemented in Python (v6)
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)
What is count occurrences of items and find top N with col in Python? (v5)
from collections import Counter words = ['apple', 'banana', 'apple', 'orange', 'apple', 'banana'] counts = Counter(words) most_common = counts.most_common(2) # [('apple', 3), ('banana', 2)]
Code for snippet for alternative constructor python classme in Python (v9)
class Date: """Date class demonstrating classmethod and staticmethod.""" def __init__(self, year, month, day): self.year, self.month, self.day = year, month, day @classmethod def from_string(cls, s): """Alternative constructor from 'YYYY-MM-DD' string.""" year, month, day = map(...
I want to understand generator based context manag with Python 3
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')
Common use case of Ensure single instance Python (v6)
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance
Python 3 I want to understand python gather coroutines resu example code (v7)
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
Tutorial on Write code for __repr__ vs __str__ python. Python (v2)
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})'
Beginner guide to Cache expensive function calls 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)
Python 3 yield from in 3 tutorial example code (v3)
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
Practical use of Can you show string manipulation python example in Python
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))
How I want to understand create list from loop python is implemented in Python (v10)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
re.match groups Python tutorial
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'))
Terminate infinite generator with Python 3 (v8)
def resource_gen(): """Generator with cleanup on close.""" print('Generator started') try: while True: yield finally: print('Generator closed - cleanup done')
Decorator using __call__ with Python 3 (v8)
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)
Code for I want to understand mutex python threading. in Python (v2)
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
Beginner guide to : BFS algorithm Python (v6)
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) ...
What is Give me an example of asyncio.gather python exampl in Python? (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 snippet for yield from in python 3. in Python (v9)
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
Practical use of Code example: named constants python enum in Python (v10)
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 snippet: Write CSV (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)
How does generator.send() tutorial tutorial work? (v5)
def accumulator(): """Generator that receives values via send() and accumulates.""" total = 0 while True: value = yield total if value is None: break total += value
Give me an example of python metaclass example.
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
Python snippet: snippet for permission flags python enum. (v5)
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
Explain Give me an example of rotating log file python. in Python
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: Find slow code Python
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 example of Write code for math functions 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 : Named constants enum is implemented in Python (v4)
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)
Explain and show code to depth first search traver Python guide (v10)
def dfs(graph, node, visited=None): if visited is None: visited = set() visited.add(node) path = [node] for neighbor in graph.get(node, []): if neighbor not in visited: path.extend(dfs(graph, neighbor, visited)) return path
Find and replace with regex with Python 3 (v10)
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
Advanced Show me how to python combination without repetiti Python example (v7)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
Understanding Give me an example of python statistics module. in Python
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
When to use Write code for python enum example. Python (v9)
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 group consecutive items tutorial is implemented in Python (v6)
import itertools def group_consecutive(lst): """Group consecutive equal elements.""" return [(k, list(v)) for k, v in itertools.groupby(lst)]
When to use How do I unpack list as function arguments python Python (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)
How I want to understand matrix to flat list python. is implemented in Python (v5)
matrix = [[1,2,3],[4,5,6],[7,8,9]] flat = [elem for row in matrix for elem in row]
When to use What does read only dataclass python look like in Python (v3)
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 snippet: Show me how to background task asyncio python in . (v9)
import asyncio async def background_work(): await asyncio.sleep(2) print('Done') async def main(): """Create and schedule a background task.""" task = asyncio.create_task(background_work()) print('Task created, doing other work') await task
Python : Metaclass __new__ complete example (v5)
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
Beginner guide to snippet for string template python. 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)
How What does asynchronous function python look like i is implemented in 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}'