anchor stringlengths 13 118 | positive stringclasses 235
values |
|---|---|
What is : generator send method example in Python? (v4) | def accumulator():
"""Generator that receives values via send() and accumulates."""
total = 0
while True:
value = yield total
if value is None:
break
total += value |
When to use Avoid circular reference tutorial Python (v3) | 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 |
Beginner guide to functools.partial example tutorial Python (v10) | 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 example of : Concurrent async tasks (v10) | 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 |
Explain What does pathlib vs os.path python look like in 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') |
Explain I want to understand submit form data python reque in Python (v7) | 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 Explain contextlib.suppress python example with co Python (v10) | from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('nonexistent.txt') # no error raised |
How Write code for how to pass data into a paused gen is implemented in Python (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 snippet for avoid circular reference python. | 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 |
Show me how to how to create a generator in python Python guide (v6) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
Explain I want to understand function that remembers outer in Python (v10) | 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 Singleton pattern tutorial (v5) | class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance |
What is Explain switch statement python with code. in Python? (v5) | def http_status(status):
match status:
case 200:
return 'OK'
case 404:
return 'Not Found'
case 500 | 503:
return 'Server Error'
case _:
return 'Unknown' |
Python example of I want to understand re.match groups python. (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: How to get all pairs from two lists Python | import itertools
def cartesian_product(a, b):
"""Compute Cartesian product of two iterables."""
return list(itertools.product(a, b)) |
Practical use of Code example: spread operator python in Python (v6) | 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} |
Beginner guide to Demonstrate min heap python in 3. 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) |
What is What is the best way to 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 |
When to use Write code for how to send values into a generato 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 |
Write a function to demonstrate sorted() with key (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) |
Understanding Explain function wrapper python with code. in 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 |
Can you show permission flags python enum example with Python 3 (v2) | from enum import Flag, auto
class Permission(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
ALL = READ | WRITE | EXECUTE
user_perm = Permission.READ | Permission.WRITE
print(Permission.READ in user_perm) # True |
Python snippet: How do I binary search python (v8) | 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 What does overload + operator python look like in complete example (v10) | 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})' |
Tutorial on I want to understand define get endpoint fastapi. Python (v6) | 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 |
What is the best way to := operator python 3.8 with Python 3 | # 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] |
Python 3 snippet for how to create a context manager python example code (v9) | 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 the yield keyword work in Python | def simple_generator():
"""Yield returns a value and preserves function local state for next invocation."""
yield "First"
yield "Second"
yield "Third" |
Python code showing coroutine send value (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 |
Write Python code for *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} |
When to use str.format example Python (v3) | # 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 does Code example: create numpy array python work? (v5) | import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = np.arange(5)
c = np.zeros((3, 3))
d = np.ones((2, 4))
print(a * 2) # [2 4 6 8 10]
print(a.mean()) # 3.0
print(a @ a) # dot product = 55 |
Python example of Show me how to regex replace python in . (v8) | import re
text = 'Hello World Python'
# Replace multiple spaces with single space
cleaned = re.sub(r'\s+', ' ', text.strip()) |
Python code showing What is the best way to mock external dependency p (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... |
Understanding snippet for python pickle module example. in Python (v7) | 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 Custom iterator class tutorial in Python? (v8) | 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 snippet: What does typing.protocol python look like in (v10) | from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
def render(obj: Drawable) -> None:
obj.draw()
# Any class with draw() satisfies Drawable without inheritance |
When to use I want to understand readable tuple python. Python (v4) | from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # access by name |
Beginner guide to Demonstrate split join strip python string in 3. Python (v10) | 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)) |
Common use case of How do I patch function python unittest 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... |
Tutorial on I want to understand check all elements satisfy co Python (v7) | 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 |
How does I want to understand run cpu bound tasks in parall work? (v4) | from multiprocessing import Pool
def square(x):
return x * x
if __name__ == '__main__':
with Pool(4) as p:
results = p.map(square, range(10))
print(results) |
Python Code example: with statement custom class python complete example (v9) | 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.... |
Explain and show code to suppress specific exceptions safely using contextlib.suppress | import contextlib
import os
with contextlib.suppress(FileNotFoundError):
os.remove('temporary_file_that_may_not_exist.tmp') |
Python What does collections.defaultdict tutorial look li complete example (v10) | 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) |
What is Can you show common python string methods example in Python? (v3) | 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)) |
Beginner guide to Explain recursive graph traversal python with code Python (v10) | 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 do I how to read and write 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) |
How implement custom context manager using __enter__ a is implemented in Python | 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 |
How : Background task asyncio is implemented in Python (v7) | 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 |
Beginner guide to mock in tests Python (v2) | 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... |
Practical use of Demonstrate how to use nonlocal in python in 3. in Python (v10) | 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 |
How to define a property with getter setter and deleter in Python in Python | class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, val):
if val <= 0:
raise ValueError("Radius must be positive")
self._radius = val
@radius.deleter
def ra... |
Give me an example of how to delegate to a sub-gen with Python 3 (v10) | 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 |
Tutorial on What does python pickle module example look like i Python (v3) | import pickle
data = {'key': [1, 2, 3], 'model': None}
# Save
with open('data.pkl', 'wb') as f:
pickle.dump(data, f)
# Load
with open('data.pkl', 'rb') as f:
loaded = pickle.load(f) |
Tutorial on Explain interface python abc module with code. Python | 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... |
What is Explain parametrized decorator python with code. in Python? (v3) | 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 ... |
Write code for how to make http request python. Python guide (v8) | import requests
response = requests.get(
'https://api.example.com/data',
headers={'Authorization': 'Bearer token'},
timeout=10
)
response.raise_for_status()
data = response.json() |
Practical use of Show me how to terminate infinite generator python in Python (v3) | def resource_gen():
"""Generator with cleanup on close."""
print('Generator started')
try:
while True:
yield
finally:
print('Generator closed - cleanup done') |
Advanced Can you show interface python abc module example Python example (v4) | 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 code showing Demonstrate loop with index python in 3. (v9) | names = ['Alice', 'Bob', 'Carol']
scores = [95, 87, 92]
# zip: pair elements
for name, score in zip(names, scores):
print(f'{name}: {score}')
# enumerate: add index
for i, name in enumerate(names, start=1):
print(f'{i}. {name}') |
What is Give me an example of typing.protocol python. in Python? (v6) | 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 |
Advanced Explain python statistics module with code. Python example (v2) | 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 |
What is Hook subclass definition in Python? | 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} |
Python snippet: Code example: filehandler python logging | 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... |
Practical use of What does python functools.partial example look li in Python (v10) | 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 |
Write a function to demonstrate Give me an example of hook subclass definition pyt (v3) | 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} |
Advanced Transform list with map Python example (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) |
Common use case of Give me an example of interface in python using pr Python (v7) | 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 |
What does callable class python look like in Python guide (v7) | class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
double = Multiplier(2)
print(double(5)) # 10 |
Understanding Explain and show code to create lightweight tuple in Python (v3) | from collections import namedtuple
Coordinate = namedtuple('Coordinate', ['lat', 'lon'])
pt = Coordinate(lat=37.77, lon=-122.41)
print(pt.lat, pt.lon) |
Python 3 Code example: python coroutine example example code (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}' |
Python snippet: What is the best way to python yield from usage (v6) | 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 |
Explain snippet for timeit python. in Python (v10) | 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 Show me how to build dictionary with comprehension (v9) | # Dict comprehension
words = ['hello', 'world', 'python']
word_lengths = {w: len(w) for w in words} |
Explain Explain build dictionary with comprehension with c in Python (v6) | # Dict comprehension
words = ['hello', 'world', 'python']
word_lengths = {w: len(w) for w in words} |
Python 3 How do I operator.attrgetter sort python example code (v6) | 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 Write code for file system operations pathlib pyt in Python (v8) | 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 snippet: Explain cartesian product in python with code. (v7) | import itertools
def cartesian_product(a, b):
"""Compute Cartesian product of two iterables."""
return list(itertools.product(a, b)) |
Python code showing Code example: avoid circular reference python (v7) | 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 snippet: Alternative constructor classmethod tutorial (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(... |
Python example of Give me an example of default value dict python. (v7) | 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) |
Give me an example of mock external dependency pyt Python guide (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... |
Practical use of Demonstrate convert dict to json python in 3. in 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) |
How does snippet for itertools.combinations example. work? | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
What is snippet for implement binary search python. in Python? (v10) | 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 |
Common use case of How do I save and load python objects Python (v9) | import pickle
data = {'key': [1, 2, 3], 'model': None}
# Save
with open('data.pkl', 'wb') as f:
pickle.dump(data, f)
# Load
with open('data.pkl', 'rb') as f:
loaded = pickle.load(f) |
Tutorial on Class method that creates instance Python | 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(... |
Python example of How do I named capture groups python re (v6) | 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 What does copy nested object python look like in Python (v6) | 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 |
I want to understand cartesian product in python. | import itertools
def cartesian_product(a, b):
"""Compute Cartesian product of two iterables."""
return list(itertools.product(a, b)) |
When to use snippet for python json module example. Python (v6) | 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 I want to understand how to send values into a gen Python example (v4) | def accumulator():
"""Generator that receives values via send() and accumulates."""
total = 0
while True:
value = yield total
if value is None:
break
total += value |
Practical use of Write code for asynchronous function python. in Python (v3) | 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}' |
When to use customize object boolean evaluation using __bool__ Python (v4) | class Account:
def __init__(self, balance):
self.balance = balance
def __bool__(self):
return self.balance > 0 |
Code for Show me how to named tuple python in . in Python (v5) | from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # access by name |
Python snippet: Show me how to python frozen dataclass example in (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 |
What is snippet for python optional vs union. in Python? (v9) | from typing import Union
def to_int(val: Union[str, float, int]) -> int:
"""Convert string, float or int to int."""
return int(val) |
When to use What does how to read and write files python look Python (v3) | # 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!') |
Tutorial on What is the best way to how to copy dict python Python (v7) | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.