Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

3 matches
Testing & modern typing easy

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.

unittest mock side_effect
Python
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…
13 0 Open
A/B testing & experimentation easy

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.

mock counter testing
Python
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 …
13 0 Open
A/B testing & experimentation medium

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.

mock unittest testing
Python
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__":…
14 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.