anchor
stringlengths
13
118
positive
stringclasses
235 values
Explain I want to understand how to make a class a decorat in Python (v5)
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)
Python Can you show how to make a class a decorator pytho complete example (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)
When to use snippet for force subclass to implement method pyt Python (v2)
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...
Beginner guide to Explain filter list python with code. Python (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)
Python code showing Code example: stateful decorator python using clas (v9)
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)
Python example of snippet for test case python. (v2)
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()
Example of how to make async HTTP GET request with with Python 3 (v5)
import aiohttp import asyncio async def fetch_json(url): async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.json()
Advanced Give me an example of pytest fixture python. Python example (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
Write Python code for memoization python functools.
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)
Common use case of How do I standard deviation python 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
What is Mock external dependency 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...
Beginner guide to What does default value dict python look like in 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)
Beginner guide to Explain shortest path unweighted graph python with Python (v10)
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) ...
Python snippet: Best practice to calculate greatest common divisor (v10)
import math def gcd_lcm(a, b): g = math.gcd(a, b) l = math.lcm(a, b) return {'gcd': g, 'lcm': l}
Python 3 Write code for group items by key python. example code (v5)
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)
Python snippet for custom sequence python class.
class MyList: def __init__(self, data): self._data = list(data) def __len__(self): return len(self._data) def __getitem__(self, index): return self._data[index]
Common use case of How do I config from environment python Python (v6)
import os from dotenv import load_dotenv load_dotenv() # reads .env file DB_URL = os.environ['DATABASE_URL'] API_KEY = os.getenv('API_KEY', 'default-key')
Code for What is the best way to create pandas dataframe py in Python (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
Demonstrate save and load python objects in Python 3.
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 does python generator expression example look (v5)
# Generator expression - memory efficient data = range(1_000_000) total = sum(x**2 for x in data if x % 2 == 0)
Python Demonstrate argparse python example in 3. complete example (v3)
import argparse parser = argparse.ArgumentParser(description='My CLI tool') parser.add_argument('input', help='Input file path') parser.add_argument('-o', '--output', default='out.txt', help='Output file') parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() print(args.input, args.ou...
How Give me an example of exception chaining python. is implemented in Python (v4)
def divide(a, b): try: return a / b except ZeroDivisionError as e: raise ValueError('b cannot be zero') from e except TypeError: raise else: print('Success') finally: print('Always runs')
Write a function to demonstrate Code example: how to use lock in python threading (v5)
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 Demonstrate how to use list comprehension python i Python (v3)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
Python Explain alternative constructor python classmethod complete example (v2)
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(...
How do I python dataclass list default value?
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 I want to understand python math module example. in Python? (v4)
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
Tutorial on slice an iterator tutorial Python (v5)
import itertools def take(n, iterable): """Return first n items of an iterable as a list.""" return list(itertools.islice(iterable, n))
How does Can you show memory efficient iteration python exa work? (v3)
# Generator expression - memory efficient data = range(1_000_000) total = sum(x**2 for x in data if x % 2 == 0)
Tutorial on Give me an example of asyncio.gather python exampl Python (v8)
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
Demonstrate benchmark function python in 3. with Python 3 (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)
Python snippet: I want to understand swallow exception python.
from contextlib import suppress with suppress(FileNotFoundError): os.remove('nonexistent.txt') # no error raised
Advanced What does match statement python look like in Python example (v10)
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 3 Write code for send json data http python. example code (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())
Understanding Code example: python counter example in Python (v8)
from collections import Counter words = 'the quick brown fox jumps over the lazy dog'.split() counts = Counter(words) print(counts.most_common(3))
Common use case of Give me an example of extract parts of string pyth Python (v4)
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 snippet: Code example: bottom up dp python (v5)
def fib_dp(n): """Fibonacci via bottom-up dynamic programming.""" if n < 2: return n dp = [0] * (n + 1) dp[1] = 1 for i in range(2, n + 1): dp[i] = dp[i-1] + dp[i-2] return dp[n]
Code for Code example: function wrapper python in Python (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
Code for Context manager protocol tutorial in Python (v8)
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 pre-fill function arguments python with code.
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 code showing Cartesian product in tutorial (v7)
import itertools def cartesian_product(a, b): """Compute Cartesian product of two iterables.""" return list(itertools.product(a, b))
Python snippet: What is the best way to sort objects by attribute (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)
Python Can you show convert dict to json python example complete example (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)
Demonstrate f string with expressions python in Python 3.
name = 'Alice' age = 30 pi = 3.14159 # Basic print(f'Hello, {name}!') # Expression print(f'In 5 years: {age + 5}') # Format spec print(f'Pi = {pi:.2f}') # Repr print(f'{name!r}')
What is : use list comprehension in Python? (v4)
# List comprehension: squares of even numbers evens_squared = [x**2 for x in range(20) if x % 2 == 0]
Can you show timeit python example?
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)
Understanding : except* syntax in 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)
Beginner guide to Code example: o(log n) search python Python (v7)
def binary_search(arr, target): lo, hi = 0, len(arr) - 1 while lo <= hi: mid = (lo + hi) // 2 if arr[mid] == target: return mid elif arr[mid] < target: lo = mid + 1 else: hi = mid - 1 return -1
Explain What is the best way to default value dict python in Python (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 All subsets of size r in Python? (v9)
import itertools def all_combinations(lst, r): """Return all r-length combinations from lst.""" return list(itertools.combinations(lst, r))
Advanced snippet for how to use dataclass in python. Python example (v6)
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
Understanding What is the best way to timeit python in Python (v3)
import cProfile, pstats, timeit # Quick benchmark elapsed = timeit.timeit('sum(range(1000))', number=10_000) print(f'10k runs: {elapsed:.3f}s') # Full profiling cProfile.run('my_function()', 'output.prof') p = pstats.Stats('output.prof').sort_stats('cumulative') p.print_stats(10)
Explain Demonstrate control class creation python in 3. in Python (v7)
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
What is Double ended queue in Python? (v9)
from collections import deque dq = deque(maxlen=5) # fixed-size circular buffer for i in range(10): dq.append(i) print(dq) # deque([5, 6, 7, 8, 9], maxlen=5)
When to use Code example: pytest conftest fixture Python (v9)
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
Code for Structural pattern matching classes tutorial in Python (v10)
from dataclasses import dataclass @dataclass class Point: x: int y: int def describe(point): match point: case Point(x=0, y=0): return 'Origin' case Point(x=0, y=y): return f'Y-axis at {y}' case Point(x=x, y=0): return f'X-axis at {x}' ca...
Python snippet for switch statement python.
def http_status(status): match status: case 200: return 'OK' case 404: return 'Not Found' case 500 | 503: return 'Server Error' case _: return 'Unknown'
How Give me an example of generator expression vs list is implemented in Python (v9)
# Generator expression - memory efficient data = range(1_000_000) total = sum(x**2 for x in data if x % 2 == 0)
Encapsulate state with closure Python tutorial
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 Demonstrate run cpu bound tasks in parallel python Python (v8)
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 create simple HTTP server using http.server in in complete example
import http.server import socketserver PORT = 8000 Handler = http.server.SimpleHTTPRequestHandler with socketserver.TCPServer(('', PORT), Handler) as httpd: print(f'Serving on port {PORT}') httpd.serve_forever()
Demonstrate how to parse command line arguments py with Python 3 (v3)
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...
Write a function to demonstrate Can you show regex groups python example (v3)
import re pattern = re.compile(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})') m = pattern.search('Date: 2024-03-15') if m: print(m.group('year'), m.group('month'), m.group('day'))
Code for Can you show implement quicksort python example in Python (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)
How does Explain python struct module example with code. work? (v3)
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 Can you show __iter__ and __next__ python example (v2)
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 Demonstrate file handling python tutorial in 3. work? (v9)
# Read entire file with open('data.txt', 'r', encoding='utf-8') as f: content = f.read() # Write to file with open('output.txt', 'w', encoding='utf-8') as f: f.write('Hello, World!')
How does What is the best way to python lru_cache decorator work? (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)
Advanced How do I search pattern in string python Python example (v2)
import re # Find all email addresses text = 'Contact alice@example.com or bob@test.org' emails = re.findall(r'[\w.+-]+@[\w-]+\.[\w.]+', text)
Python What is the best way to python nested loop replace complete example
import itertools def cartesian_product(a, b): """Compute Cartesian product of two iterables.""" return list(itertools.product(a, b))
Understanding Mock external dependency in 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...
Tutorial on Show me how to standard deviation python in . Python (v9)
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 What is the best way to assert equal python unitte (v4)
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()
Tutorial on I want to understand swallow exception python. Python (v9)
from contextlib import suppress with suppress(FileNotFoundError): os.remove('nonexistent.txt') # no error raised
Common use case of What does shuffle list python look like in Python (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
Tutorial on What does decorator using __call__ python look lik Python (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)
Python snippet: I want to understand add behaviour with mixin pyth (v2)
class SerializeMixin: def to_dict(self): return self.__dict__ def to_json(self): import json return json.dumps(self.to_dict()) class User(SerializeMixin): def __init__(self, name, email): self.name = name self.email = email
When to use Explain avoid circular reference python with code. Python (v8)
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
How does What does pytest fixture python look like in work? (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
Write a function to demonstrate snippet for default value dict python. (v9)
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 the best way to lightweight data object python?
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(3, 4) print(p.x, p.y) # access by name
Give me an example of function wrapper python. with Python 3 (v10)
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
Common use case of How do I custom print for python class Python (v4)
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 star unpacking example tutorial complete example (v5)
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}
Demonstrate pydantic model python example in Python 3.
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...
Beginner guide to What does duck typing with type hints python look 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
Python How do I define callback signature with typing.Cal complete example (v2)
from typing import Callable def process_items(items: list[int], func: Callable[[int], int]) -> list[int]: return [func(x) for x in items]
Python snippet: Best practice to create FastAPI GET endpoint with (v2)
from fastapi import FastAPI, Query from pydantic import BaseModel app = FastAPI() class User(BaseModel): name: str tier: str @app.get('/users', response_model=list[User]) def get_users(tier: str = Query('free', enum=['free', 'pro'])): return [{'name': 'Alice', 'tier': tier}]
How does Explain and show code to define Pydantic BaseModel work? (v8)
from pydantic import BaseModel, Field, field_validator class User(BaseModel): id: int email: str age: int = Field(ge=0, le=120) @field_validator('email') def validate_email(cls, v): if '@' not in v: raise ValueError('Invalid email') return v
Python example of Give me an example of when to use classmethod pyth (v2)
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 is parse query parameters and URL components with url in Python? (v4)
from urllib.parse import urlparse, parse_qs url = 'https://api.example.com/search?q=python&page=2' parsed = urlparse(url) params = parse_qs(parsed.query) # {'q': ['python'], 'page': ['2']}
Explain Write code for how to use logging in python. in Python (v5)
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)
When to use Trie data structure Python (v2)
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...
Show me how to group items by key python in . with Python 3 (v9)
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)
Explain Named capture groups re in Python (v9)
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'))
How snippet for partial function application python. is implemented in Python (v3)
from functools import partial def power(base, exp): return base ** exp square = partial(power, exp=2) cube = partial(power, exp=3) print(square(4)) # 16 print(cube(3)) # 27
@dataclass decorator Python tutorial
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
Python snippet for how to write a decorator 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
What is I want to understand group list by key python. in Python? (v7)
import itertools def group_consecutive(lst): """Group consecutive equal elements.""" return [(k, list(v)) for k, v in itertools.groupby(lst)]
Advanced Explain class based decorator python with code. Python example (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)