Цена за 48 часов в ленте | 1000,00 |
Цена за 1 час закрепления | N/A |
Взаимопиар | Нет |
казино, букмекеры |
|
def test_sum():
assert sum([1, 2, 3]) == 6
assert sum([-1, 1]) == 0
from hypothesis import given
import hypothesis.strategies as st
@given(st.lists(st.integers()))
def test_sum_properties(numbers):
assert sum(numbers) == sum(reversed(numbers))
assert sum(numbers + [0]) == sum(numbers)
import click
@click.group()
def cli():
"""Утилита для работы с файлами"""
pass
@cli.command()
@click.argument('path')
@click.option('--lines', '-l', is_flag=True, help='Показать количество строк')
def analyze(path, lines):
"""Анализирует файл и выводит статистику"""
try:
with open(path) as f:
content = f.readlines()
if lines:
click.echo(f'Количество строк: {len(content)}')
except FileNotFoundError:
click.secho('Файл не найден! 😱', fg='red')
if __name__ == '__main__':
cli()
@cli.command()
@click.argument('path')
def process(path):
"""Обрабатывает файлы с прогресс-баром"""
files = os.listdir(path)
with click.progressbar(files, label='Обработка файлов') as bar:
for f in bar:
# что-то делаем с файлом
time.sleep(0.1)
click.secho('Внимание! 🚨', fg='yellow', bold=True)
click.secho('Ошибка! ❌', fg='red')
click.secho('Успех! ✅', fg='green')
if click.confirm('Уверены, что хотите удалить все файлы? 🤔'):
click.echo('Поехали! 🚀')
print(bool(-1)) # Результат: True
# Старый подход с os.path
import os.path
file_path = os.path.join('data', 'users', 'config.json')
parent_dir = os.path.dirname(file_path)
file_name = os.path.basename(file_path)
# Новый подход с pathlib
from pathlib import Path
file_path = Path('data') / 'users' / 'config.json'
parent_dir = file_path.parent
file_name = file_path.name
path = Path('config.json')
if path.exists():
print('Файл существует!')
Path('nested/directories/structure').mkdir(parents=True, exist_ok=True)
# Найти все .py файлы в текущей директории
python_files = list(Path('.').glob('*.py'))
path = Path('document.pdf')
print(path.suffix) # .pdf
print(path.stem) # document
config_path = (Path.home() / 'projects' / 'app' / 'config.json')
if config_path.exists():
data = json.loads(config_path.read_text())
with Path('log.txt').open('w') as f:
f.write('Logging started')
def create_power_function(power):
def power_func(x):
return x ** power
return power_func
# Создаём функции на лету
square = create_power_function(2)
cube = create_power_function(3)
import types
def create_dynamic_function(func_name, args, body):
namespace = {}
func_code = f"def {func_name}({', '.join(args)}):\n{body}"
exec(func_code, globals(), namespace)
return namespace[func_name]
# Магия в действии
greet = create_dynamic_function(
"greet",
["name"],
" return f'Привет, {name}!'"
)
# Без slots
class User:
def __init__(self, name, age):
self.name = name
self.age = age
# Со slots
class OptimizedUser:
__slots__ = ['name', 'age']
def __init__(self, name, age):
self.name = name
self.age = age
class DataPoint:
__slots__ = ['timestamp', 'value', 'sensor_id']
def __init__(self, timestamp, value, sensor_id):
self.timestamp = timestamp
self.value = value
self.sensor_id = sensor_id
# Представьте, что таких объектов у вас миллионы
data_points = [DataPoint(time.time(), random.random(), i) for i in range(1_000_000)]
import ast
code = """
def calculate_sum(a, b):
result = a + b
print(f"Sum: {result}")
return result
"""
# Создаем AST
tree = ast.parse(code)
# Анализируем структуру
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
print(f"Найдена функция: {node.name}")
elif isinstance(node, ast.Name):
print(f"Найдена переменная: {node.id}")
class DebugTransformer(ast.NodeTransformer):
def visit_FunctionDef(self, node):
# Добавляем отладочный print в начало каждой функции
debug_print = ast.Expr(
value=ast.Call(
func=ast.Name(id='print', ctx=ast.Load()),
args=[ast.Constant(value=f"Вызов функции {node.name}")],
keywords=[]
)
)
node.body.insert(0, debug_print)
return node
# Применяем трансформацию
transformed = DebugTransformer().visit(tree)
class StringOptimizer(ast.NodeTransformer):
def visit_BinOp(self, node):
# Оптимизация конкатенации строк
if isinstance(node.op, ast.Add):
if isinstance(node.left, ast.Constant) and isinstance(node.right, ast.Constant):
if isinstance(node.left.value, str) and isinstance(node.right.value, str):
return ast.Constant(value=node.left.value + node.right.value)
return node
class ComplexityAnalyzer(ast.NodeVisitor):
def __init__(self):
self.complexity = 0
def visit_If(self, node):
self.complexity += 1
self.generic_visit(node)
def visit_For(self, node):
self.complexity += 2
self.generic_visit(node)
def visit_While(self, node):
self.complexity += 2
self.generic_visit(node)
# Использование
analyzer = ComplexityAnalyzer()
analyzer.visit(tree)
print(f"Сложность кода: {analyzer.complexity}")
from unittest.mock import patch
import asyncio
async def fetch_data(url):
# Реальный запрос к API
...
@patch('your_module.fetch_data')
async def test_process_data(mock_fetch):
mock_fetch.return_value = {'key': 'value'}
result = await process_data('http://api.example.com')
assert result == 'processed value'
import asyncio
async def test_order_of_execution():
event = asyncio.Event()
results = []
async def task1():
await event.wait()
results.append(1)
async def task2():
results.append(2)
event.set()
await asyncio.gather(task1(), task2())
assert results == [2, 1]
import pytest
import asyncio
@pytest.mark.asyncio
async def test_long_running_task():
with pytest.raises(asyncio.TimeoutError):
await asyncio.wait_for(never_ending_task(), timeout=1.0)
import pytest
import asyncio
@pytest.fixture
async def database():
db = await create_database_connection()
yield db
await db.close()
@pytest.mark.asyncio
async def test_database_query(database):
result = await database.fetch('SELECT * FROM users')
assert len(result) > 0
pytest -n auto your_test_file.py
from pathlib import Path
downloads = Path.home() / 'Downloads'
for file in downloads.glob('*.pdf'):
print(f"Нашел PDF: {file.name}")
import os
from pathlib import Path
def create_project_structure(name):
base = Path(name)
folders = ['src', 'tests', 'docs', 'resources']
files = ['README.md', 'requirements.txt', '.gitignore']
for folder in folders:
(base / folder).mkdir(parents=True, exist_ok=True)
for file in files:
(base / file).touch()
print(f"Проект {name} создан! 🎉")
create_project_structure("super_puper_project")
import hashlib
from collections import defaultdict
def find_duplicates(directory):
hash_map = defaultdict(list)
for path in Path(directory).rglob('*'):
if path.is_file():
file_hash = hashlib.md5(path.read_bytes()).hexdigest()
hash_map[file_hash].append(path)
return {hash: paths for hash, paths in hash_map.items() if len(paths) > 1}
dupes = find_duplicates('/path/to/directory')
for hash, files in dupes.items():
print(f"Найдены дубликаты: {', '.join(str(f) for f in files)}")
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class Sorter(FileSystemEventHandler):
def on_created(self, event):
if not event.is_directory:
file = Path(event.src_path)
dest = file.parent / file.suffix[1:]
dest.mkdir(exist_ok=True)
file.rename(dest / file.name)
print(f"Файл {file.name} перемещен в {dest}")
path = "/path/to/watch"
event_handler = Sorter()
observer = Observer()
observer.schedule(event_handler, path, recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
import asyncio
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.get_event_loop()
loop.set_default_executor(concurrent.futures.ThreadPoolExecutor(max_workers=10))
sem = asyncio.Semaphore(10)
async def controlled_task(i):
async with sem:
# Ваш асинхронный код здесь
await asyncio.sleep(1)
print(f"Задача {i} выполнена!")
class AsyncContextManager:
async def __aenter__(self):
print("Entering the matrix...")
await asyncio.sleep(1)
return self
async def __aexit__(self, exc_type, exc, tb):
print("Exiting the matrix...")
await asyncio.sleep(1)
async def main():
async with AsyncContextManager() as manager:
print("We're in!")
async def async_range(start, stop):
for i in range(start, stop):
await asyncio.sleep(0.1)
yield i
async def main():
async for num in async_range(0, 10):
print(num)