Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
How to Mock a Liveness Check and Restart a Process in Python
Simulate a failing process and restart it after a liveness check fails, using a mock class and a liveness loop.
import subprocess
import sys
import time
import os
class ProcessMock:
def __init__(self, name, fail_after_seconds=3):
self.name = name
self.fail_after = fail_after_seconds
self.start_time = None
self.is_running = False
def start(self):
self.start_time = time.time()
…
How to Smoke Test a Deployment in Python with unittest.mock
Run a post-deploy smoke test by mocking the deployment status check to verify your health-check logic returns PASS/FAIL.
import unittest
from unittest.mock import Mock, patch
class DeploymentService:
def check_status(self):
return "unknown"
def smoke_test_deploy():
service = DeploymentService()
with patch.object(service, "check_status", return_value="healthy") as mock_check:
status = service.check_status()
…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.