anchor
stringlengths
13
118
positive
stringclasses
235 values
I want to understand parse json string python. Python guide (v3)
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)
Practical use of Can you show profile python code performance examp in Python (v6)
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 code showing Write code for argparse python example.
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...
Python snippet: Explain observer pattern python with code. (v8)
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)
Common use case of Resume a function from where it left Python (v5)
def count_up(n): """Generator that yields numbers 0 to n-1.""" for i in range(n): yield i
Explain What does collections.ordereddict tutorial look li in Python (v9)
from collections import OrderedDict od = OrderedDict() od['a'] = 1 od['b'] = 2 od.move_to_end('a') # move 'a' to end
Code for Give me an example of async def python tutorial. in Python
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}'
Beginner guide to Explain create list from loop python comprehension Python (v4)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
Understanding I want to understand how to make a class a decorat in Python (v10)
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)
How I want to understand function that remembers outer is implemented in Python (v5)
def make_counter(start=0): """Closure that maintains a counter.""" count = [start] def increment(by=1): count[0] += by return count[0] return increment
Explain What is the best way to python f-string example in Python (v7)
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}')
Write a function to demonstrate How do I exceptiongroup python example (v3)
# Python 3.11+ ExceptionGroup try: raise ExceptionGroup('several errors', [ ValueError('bad value'), TypeError('bad type'), ]) except* ValueError as eg: print('ValueErrors:', eg.exceptions) except* TypeError as eg: print('TypeErrors:', eg.exceptions)
How do I re.match groups python Python guide
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'))
Code for Give me an example of sort by multiple keys python in Python (v4)
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 What does random choice python look like in (v9)
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
Beginner guide to Explain parametrize pytest with code. Python (v6)
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
Write a function to demonstrate Best practice to run I/O bound requests in paralle (v8)
from concurrent.futures import ThreadPoolExecutor import urllib.request def fetch(url): with urllib.request.urlopen(url) as r: return r.status urls = ['https://httpbin.org/get'] * 5 with ThreadPoolExecutor(max_workers=5) as pool: statuses = list(pool.map(fetch, urls))
Regex replace Python tutorial
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
Explain filter rows pandas python with code.
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
Explain What does function wrapper python look like in in Python (v9)
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
snippet for profile python code performance. with Python 3 (v5)
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 python metaclass example. Python guide (v4)
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
How does What is the best way to immutable dataclass python work? (v9)
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
Code for What does profile python code performance look lik in 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)
How What is the best way to __get__ __set__ __delete__ is implemented in Python (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...
How : Group by pandas is implemented in Python (v5)
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
Advanced What is the best way to nonlocal keyword python ex Python example (v9)
def make_adder(n): """Use nonlocal to modify enclosing scope variable.""" total = 0 def add(x): nonlocal total total += x + n return total return add
Beginner guide to Function that remembers outer scope Python (v5)
def make_counter(start=0): """Closure that maintains a counter.""" count = [start] def increment(by=1): count[0] += by return count[0] return increment
Code for Can you show simple rest api flask python example in Python (v3)
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}!'})
Code for Write code for type safe data model python. in Python (v3)
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 3 Demonstrate interface python abc module in 3. example code (v3)
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...
How does Can you show contextlib.contextmanager python exam work? (v3)
from contextlib import contextmanager @contextmanager def timer(label=''): """Context manager that times a block.""" import time start = time.perf_counter() try: yield finally: elapsed = time.perf_counter() - start print(f'{label}: {elapsed:.4f}s')
Python snippet: snippet for binary search algorithm python. (v9)
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
Beginner guide to Write code for avoid keyerror python dictionary. Python (v6)
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)
decorator example tutorial Python guide (v9)
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
Practical use of Demonstrate replace pattern in string python in 3 in Python (v2)
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
Practical use of What does ordereddict python example look like in in Python (v9)
from collections import OrderedDict od = OrderedDict() od['a'] = 1 od['b'] = 2 od.move_to_end('a') # move 'a' to end
Advanced Demonstrate python typing module tutorial in 3. Python example (v4)
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 How do I speed up recursive function python cachin (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 Demonstrate format string python 3.6 in 3. complete example (v8)
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}')
Practical use of Show me how to python string representation of obj in Python (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})'
define __repr__ and __str__ with Python 3 (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})'
Python snippet: struct module example (v6)
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)
Explain Min heap tutorial in Python (v2)
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)
What does test case python look like in Python?
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 3 Write code for generator function that pauses exe example code (v10)
def count_up(n): """Generator that yields numbers 0 to n-1.""" for i in range(n): yield i
Python 3 Functional programming example code (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)
Explain how to write a decorator in python with co Python guide (v9)
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 the best way to python requests post example?
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())
Python code showing : use Lock in threading (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 : Callable class Python example
class Multiplier: def __init__(self, factor): self.factor = factor def __call__(self, x): return x * self.factor double = Multiplier(2) print(double(5)) # 10
snippet for iterate over lines in file python. Python guide (v5)
# Memory-efficient line-by-line reading with open('large_file.txt', encoding='utf-8') as f: for line in f: process(line.rstrip('\n'))
Understanding Code example: partial function application python in Python (v9)
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
Common use case of Explain sorted() with key python with code. Python (v10)
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)
What is Can you show memory efficient class python example 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
Explain Show me how to itertools.groupby python example in in Python (v3)
import itertools def group_consecutive(lst): """Group consecutive equal elements.""" return [(k, list(v)) for k, v in itertools.groupby(lst)]
How does Code example: staticmethod vs classmethod python work? (v7)
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(...
Advanced Code example: how to make http request python Python example (v9)
import requests response = requests.get( 'https://api.example.com/data', headers={'Authorization': 'Bearer token'}, timeout=10 ) response.raise_for_status() data = response.json()
Code example: python threading example Python guide
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 snippet: Show me how to build dictionary with comprehension (v4)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
Explain rotating log file python with code. with Python 3 (v9)
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...
Demonstrate debug info warning error python logging in Python 3.
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 does Write code for fastapi route example. work? (v9)
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 3 I want to understand generate random number python example code (v4)
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: Can you show non blocking io python asyncio exampl (v5)
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}'
Explain Binary file format tutorial in Python (v9)
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 example of code to sort list of dictionaries by a specific ke (v3)
users = [{'name': 'Bob', 'age': 30}, {'name': 'Alice', 'age': 25}] sorted_users = sorted(users, key=lambda u: u['age'])
Iterate over lines in file Python tutorial
# Memory-efficient line-by-line reading with open('large_file.txt', encoding='utf-8') as f: for line in f: process(line.rstrip('\n'))
Code for implement singleton pattern or customize object cr in Python (v2)
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance
Multithreading Python tutorial
import threading def worker(name): print(f'Thread {name} starting') threads = [threading.Thread(target=worker, args=(i,)) for i in range(5)] for t in threads: t.start() for t in threads: t.join()
Can you show how to serialize python objects examp with Python 3 (v10)
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)
What is BaseModel pydantic tutorial in Python?
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...
Create a closure that maintains state between calls using nonlocal
def make_counter(start=0): count = start def step(): nonlocal count count += 1 return count return step
When to use : Pandas read csv Python (v9)
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
Show me how to sort by multiple keys python 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']))
How does frozen dataclass example tutorial work? (v5)
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
What is Write code for old style string formatting python in Python? (v7)
# 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)
What is the best way to python sort lambda example with Python 3 (v2)
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)
Give me an example of how to use enum in python. Python guide (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)
Practical use of I want to understand async def python tutorial. in Python (v10)
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}'
What does switch statement python look like in with Python 3 (v7)
def http_status(status): match status: case 200: return 'OK' case 404: return 'Not Found' case 500 | 503: return 'Server Error' case _: return 'Unknown'
Tutorial on What does consecutive grouping python look like in Python (v8)
import itertools def group_consecutive(lst): """Group consecutive equal elements.""" return [(k, list(v)) for k, v in itertools.groupby(lst)]
Demonstrate python readline example in Python 3.
# Memory-efficient line-by-line reading with open('large_file.txt', encoding='utf-8') as f: for line in f: process(line.rstrip('\n'))
Code example: __add__ python example with Python 3 (v9)
class Vector: def __init__(self, x, y): self.x, self.y = x, y def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __repr__(self): return f'Vector({self.x}, {self.y})'
Explain Give me an example of how to use pathlib python. in Python (v9)
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 showing How do I iterate two lists simultaneously 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}')
Load JSON file Python tutorial
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)
Common use case of Demonstrate how to call parent class method python Python (v5)
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 example of Give me an example of create pandas dataframe pyth (v10)
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
use dataclass in tutorial with Python 3 (v7)
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
Code for What does replace pattern in string python look li in Python (v8)
import re text = 'Hello World Python' # Replace multiple spaces with single space cleaned = re.sub(r'\s+', ' ', text.strip())
What is Can you show ordereddict python example example in Python? (v6)
from collections import OrderedDict od = OrderedDict() od['a'] = 1 od['b'] = 2 od.move_to_end('a') # move 'a' to end
What is Explain python zip example with code. in Python?
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}')
: := operator 3.8 Python guide (v10)
# 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]
Practical use of I want to understand dictionary from two lists pyt in Python (v5)
# Dict comprehension words = ['hello', 'world', 'python'] word_lengths = {w: len(w) for w in words}
Python 3 What is the best way to custom equality python cla example code (v2)
class Point: def __init__(self, x, y): self.x, self.y = x, y def __eq__(self, other): return isinstance(other, Point) and self.x == other.x and self.y == other.y def __hash__(self): return hash((self.x, self.y))
Beginner guide to How do I refactor nested loops using yield from Python (v4)
def flatten(nested): """Flatten nested iterables using yield from.""" for item in nested: if hasattr(item, '__iter__') and not isinstance(item, str): yield from flatten(item) else: yield item
Python 3 snippet for event listener python. example code (v5)
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)
Write a function to demonstrate I want to understand type hint that allows none py (v7)
from typing import Union def to_int(val: Union[str, float, int]) -> int: """Convert string, float or int to int.""" return int(val)
How does snippet for write csv python. work?
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)