Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

2 matches
Modern tooling easy

How to Use pytest Fixtures and conftest.py for Shared Setup in Python

Learn how to define reusable pytest fixtures for shared setup and use them to keep tests clean and maintainable.

pytest fixtures conftest
Python
import pytest

class Calculator:
    def add(self, a, b):
        return a + b

    def multiply(self, a, b):
        return a * b


@pytest.fixture
def calc():
    return Calculator()


@pytest.fixture
def sample_numbers():
    return (3, 5)


def test_add(calc, sample_numbers):
    a, b = sample_numbers
    assert c…
13 0 Open
Testing & modern typing easy

How to Share Fixtures Across Tests with pytest conftest

Learn how to define pytest fixtures in conftest.py and control their scope (function, module, session) so every test in a directory reuses the same setup and teardown.

pytest fixtures conftest
Python
import pytest

@pytest.fixture
def sample_data():
    """Simple fixture available to all tests in this directory."""
    return {"name": "Alice", "age": 30}

@pytest.fixture(scope="session")
def session_data():
    """Fixture created once per test session."""
    return {"session_id": 12345}

@pytest.fixture(scope="mo…
13 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.