anchor stringlengths 13 118 | positive stringclasses 235
values |
|---|---|
Python What is the best way to permission flags python en complete example (v3) | 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 |
Understanding Map keys to values one liner in Python (v2) | # Dict comprehension
words = ['hello', 'world', 'python']
word_lengths = {w: len(w) for w in words} |
Beginner guide to How do I how to throw exception into generator pyt Python (v4) | def safe_gen():
"""Generator that handles injected exceptions."""
try:
while True:
yield
except ValueError as e:
print(f'Caught: {e}')
yield 'recovered' |
Python code showing Write code for python dataclass list default valu (v9) | from dataclasses import dataclass, field
@dataclass
class Team:
name: str
members: list = field(default_factory=list)
_id: int = field(default=0, repr=False) |
Write a function to demonstrate Explain regular expression python with code. (v10) | import re
# Find all email addresses
text = 'Contact alice@example.com or bob@test.org'
emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', text) |
What is the best way to python cprofile example Python guide (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) |
How define structural protocol for duck typing interfa is implemented in Python (v9) | from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
def render(obj: Drawable):
obj.draw() |
Advanced snippet for extend exception class python. Python example | 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 |
Understanding Show me how to extend exception class python in . in Python (v3) | class ValidationError(Exception):
"""Raised when input validation fails."""
def __init__(self, field: str, msg: str):
self.field = field
super().__init__(f'{field}: {msg}')
class NetworkError(RuntimeError):
"""Raised on network failures."""
pass |
How Example of how to read and write JSON file safely is implemented in Python (v5) | import json
data = {'name': 'Alice', 'roles': ['admin', 'user']}
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
with open('data.json', 'r', encoding='utf-8') as f:
loaded = json.load(f) |
Give me an example of python functools.cache example. | 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) |
What is the best way to resource management python context manager? | 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 python json module example with code. with Python 3 (v7) | 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) |
When to use snippet for python string representation of object Python (v6) | class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f'Point({self.x!r}, {self.y!r})'
def __str__(self):
return f'({self.x}, {self.y})' |
Python code showing Shuffle list (v10) | 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: What does except* python syntax look like in (v10) | # 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) |
What is I want to understand duck typing with type hints p in 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 |
Write a function to demonstrate What does random sample python look like in (v8) | 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 example of Can you show memory efficient iteration python exa (v2) | # Generator expression - memory efficient
data = range(1_000_000)
total = sum(x**2 for x in data if x % 2 == 0) |
How Copy nested object is implemented in Python (v10) | 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 |
Beginner guide to Give me an example of python exceptiongroup 3.11. Python (v7) | # 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) |
: FileHandler logging with Python 3 (v5) | import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger('myapp')
logger.setLevel(logging.DEBUG)
fh = RotatingFileHandler('app.log', maxBytes=1_000_000, backupCount=3)
fh.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
logger.addHandler(fh)
logger.add... |
Code for Code example: permission flags python enum in Python (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 code showing Explain itertools.groupby python example with code (v2) | import itertools
def group_consecutive(lst):
"""Group consecutive equal elements."""
return [(k, list(v)) for k, v in itertools.groupby(lst)] |
How How do I regular expression python is implemented in Python (v3) | import re
# Find all email addresses
text = 'Contact alice@example.com or bob@test.org'
emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', text) |
What is How do I profile python code performance in Python? (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) |
Python code showing Write code for how to sort list by custom key pyt (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) |
How **kwargs example tutorial is implemented in Python (v9) | 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) |
When to use Demonstrate dataclasses.field python example in 3 Python (v4) | from dataclasses import dataclass, field
@dataclass
class Team:
name: str
members: list = field(default_factory=list)
_id: int = field(default=0, repr=False) |
Advanced I want to understand pickle dump and load python. Python example (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) |
Python snippet: What is the best way to yield statement python tut (v6) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
Python example of : Readable tuple (v10) | from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # access by name |
Python Demonstrate python recursive sort example in 3. complete example (v7) | def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right) |
Show me how to binary search python 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 |
Python code showing Explain group list by key python with code. (v7) | import itertools
def group_consecutive(lst):
"""Group consecutive equal elements."""
return [(k, list(v)) for k, v in itertools.groupby(lst)] |
What is the best way to combine multiple lists python itertools? | 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] |
Python snippet: How do I asyncio.gather python example (v2) | 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 |
: Reusable test setup pytest with Python 3 (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 |
Understanding What does make python object hashable look like in in Python (v9) | 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)) |
Explain := operator 3.8 tutorial in Python | # 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] |
Write a function to demonstrate Write code for memory efficient iteration python. (v10) | # Generator expression - memory efficient
data = range(1_000_000)
total = sum(x**2 for x in data if x % 2 == 0) |
Code example: cartesian product in python Python guide (v6) | import itertools
def cartesian_product(a, b):
"""Compute Cartesian product of two iterables."""
return list(itertools.product(a, b)) |
Show me how to enumerate python example 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}') |
Python snippet: Show me how to terminate infinite generator python (v9) | def resource_gen():
"""Generator with cleanup on close."""
print('Generator started')
try:
while True:
yield
finally:
print('Generator closed - cleanup done') |
Common use case of What does how to make class iterable python look l Python (v7) | 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 |
How does Setup and teardown pytest tutorial work? (v7) | 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 |
Python example of How do I python functools.cache example (v4) | 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) |
Understanding Give me an example of generator function that paus in Python (v9) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
Python snippet: Can you show how to throw exception into generator (v5) | def safe_gen():
"""Generator that handles injected exceptions."""
try:
while True:
yield
except ValueError as e:
print(f'Caught: {e}')
yield 'recovered' |
Beginner guide to snippet for interactive generator python. Python (v10) | def accumulator():
"""Generator that receives values via send() and accumulates."""
total = 0
while True:
value = yield total
if value is None:
break
total += value |
What is Explain how to get all combinations python with co in Python? (v3) | import itertools
def all_combinations(lst, r):
"""Return all r-length combinations from lst."""
return list(itertools.combinations(lst, r)) |
How does snippet for background task asyncio python. work? (v6) | 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 |
Common use case of Factory method example tutorial Python (v10) | 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() |
Common use case of use yield in Python (v5) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
Write a function to demonstrate Write code for itertools.chain example python. (v10) | 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] |
How does Write code for python threading example. work? (v2) | 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() |
Write a function to demonstrate : chain iterators together (v9) | 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 Reduce memory usage class slots Python (v10) | class Point:
__slots__ = ('x', 'y') # restrict to only x, y
def __init__(self, x, y):
self.x = x
self.y = y
# No __dict__ => saves memory for millions of instances |
Explain Demonstrate ensure single instance python in 3. in Python | class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance |
When to use What is the best way to how to create custom excep Python (v4) | 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 |
When to use Demonstrate create objects based on type python in Python (v5) | 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() |
Write a function to demonstrate Write code for mergesort algorithm python. | def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(l, r):
result = []
i = j = 0
while i < len(l) and j < len(r):
if l[i] <= r[j]:
result.append(... |
Python 3 : mock in tests example code | 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... |
Common use case of Code example: sort list of dicts python 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'])) |
How does yield from keyword example work? (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 |
Tutorial on Give me an example of pre-fill function arguments Python (v4) | 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 |
Advanced Show me how to python lazy evaluation with yield i Python example (v7) | def count_up(n):
"""Generator that yields numbers 0 to n-1."""
for i in range(n):
yield i |
How Demonstrate how to create a closure python in 3. 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 |
Beginner guide to dataclass field with default factory tutorial Python (v9) | from dataclasses import dataclass, field
@dataclass
class Team:
name: str
members: list = field(default_factory=list)
_id: int = field(default=0, repr=False) |
What is the best way to how to make a class a deco with Python 3 | 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) |
Beginner guide to Write code for how to create a context manager py Python (v6) | 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.... |
Python code showing I want to understand raise custom exception python (v6) | 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 |
Beginner guide to Can you show structural pattern matching python 3. Python (v4) | def http_status(status):
match status:
case 200:
return 'OK'
case 404:
return 'Not Found'
case 500 | 503:
return 'Server Error'
case _:
return 'Unknown' |
Show me how to python json module example in . Python guide | 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 Example of how to enforce timeout on an asynchrono Python example (v6) | import asyncio
async def slow_task():
await asyncio.sleep(5)
return "Done"
async def main():
try:
async with asyncio.timeout(1.0):
await slow_task()
except TimeoutError:
print("Task timed out!") |
Explain Custom equality class tutorial in Python | 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)) |
How to implement singleton pattern with a class decorator in Python | def singleton(cls):
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance |
Python example of Explain pack unpack binary data python with code. (v7) | 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) |
Write a function to demonstrate Code example: __add__ python example (v5) | 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})' |
Write a function to demonstrate Autocomplete data structure tutorial (v9) | class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.is_end... |
Python code showing Write code for callable class python. (v9) | class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
double = Multiplier(2)
print(double(5)) # 10 |
Python code showing Write code for raise custom exception python. (v4) | 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 code showing Code example: 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 snippet: How do I standard deviation python (v4) | 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 |
Practical use of What does patch function python unittest look like in Python (v6) | 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... |
Code for Code example: deep copy python in Python (v8) | 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 |
Practical use of code to format and inspect exception stack trace w in Python (v10) | import traceback
try:
1 / 0
except ZeroDivisionError:
error_msg = traceback.format_exc()
print(f"Captured traceback:\n{error_msg}") |
How does Can you show mutex python threading example work? (v3) | 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 |
Python snippet: snippet for pytest fixture python. (v5) | 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 |
Common use case of Give me an example of flask route example python. Python (v9) | 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}!'}) |
Practical use of Demonstrate custom equality python class in 3. in Python (v10) | 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)) |
Python example of Write code for processpoolexecutor python example (v6) | 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: How to use list comprehension Python | # List comprehension: squares of even numbers
evens_squared = [x**2 for x in range(20) if x % 2 == 0] |
Common use case of Give me an example of copy nested object python. Python (v5) | 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 |
Python code showing : DFS iterative (v9) | 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 |
Code for : __add__ example in Python (v4) | 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})' |
What is Show me how to python __slots__ memory optimizatio in Python? (v10) | class Point:
__slots__ = ('x', 'y') # restrict to only x, y
def __init__(self, x, y):
self.x = x
self.y = y
# No __dict__ => saves memory for millions of instances |
When to use How do I := operator python 3.8 Python (v5) | # 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] |
What is Give me an example of python unittest example. in Python? (v8) | 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() |
Code for Explain python protocol typing example with code. in Python (v8) | from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
def render(obj: Drawable) -> None:
obj.draw()
# Any class with draw() satisfies Drawable without inheritance |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.