Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to use unittest mock side_effect with a sequence in Python
Demonstrates using Mock.side_effect with a list to return different values per call and raise an exception at a specific call in unittest.
import unittest
from unittest.mock import Mock
class TestMockSideEffectSequence(unittest.TestCase):
def test_side_effect_sequence(self):
mock = Mock()
mock.side_effect = [1, 2, 3, Exception("boom")]
self.assertEqual(mock(), 1)
self.assertEqual(mock(), 2)
self.asser…
How to Create a Mock That Returns Inverse Counter Values in Python
Builds a Mock whose side_effect returns the inverse (1/count) of each Counter value, defaulting to 0.0 for unseen keys.
from collections import Counter
from unittest.mock import Mock
def inverse_mock(counter: Counter) -> Mock:
"""
Return a Mock that mimics the inverse of a Counter:
each key returns a value representing the inverse of its count.
The Mock's side_effect maps keys to their inverse counts.
"""
mock …
How to Mock Sequential Calls in Python with unittest.mock
Use Mock.side_effect to return a different result for each sequential call and verify the call order with assert_has_calls.
import unittest
from unittest.mock import Mock
class Service:
def fetch(self, item_id):
raise NotImplementedError
def process_items(service, ids):
results = []
for item_id in ids:
result = service.fetch(item_id)
results.append(result)
return results
if __name__ == "__main__":…
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.