fake_repo = type('FakeRepo', (), {'save': lambda self, item: None})()
Testing Patterns

Meaning

Uses Python's three-argument type() call to dynamically construct a class with stub methods, then immediately instantiates it into an object. It eliminates the boilerplate of defining a full class when all you need is a lightweight test double that accepts method calls without real behavior. You reach for it during unit testing when a dependency must satisfy an interface but no actual logic is required.

Primary Function

Test doubles

Communicative Purpose

Avoids defining full classes for lightweight test stubs by dynamically creating minimal fake objects inline.

Pattern

type('classname', (), {'methodname': lambda self, arg: None})()

Core Structure

type(..., (), {...: lambda ...: ...})()

Função primária

Test doubles

Propósito comunicativo

Avoids defining full classes for lightweight test stubs by dynamically creating minimal fake objects inline.

Situações de gatilho

Unit testing: needing a repository or service stub that accepts method calls but performs no real work. Test-driven development: creating a quick stand-in for a dependency without polluting the test module with class definitions. Prototyping: spinning up a minimal object with a required interface for quick experimentation.

Contextos

Python testing, pytest, unittest, dependency injection patterns, repository pattern implementations

Padrão

type('classname', (), {'methodname': lambda self, arg: None})()

Estrutura central

type(..., (), {...: lambda ...: ...})()

Slots de substituição

classname: str, methodname: str, arg: str, return: any

Colocados típicos

  • unittest.mock.MagicMock
  • unittest.mock.patch
  • pytest fixtures
  • dependency injection
  • repository pattern

Substituições comuns

  • unittest.mock.MagicMock: more feature-rich with call tracking and return value configuration
  • but heavier and less transparent. Simple stub class definition: clearer and more IDE-friendly
  • but requires more boilerplate lines. types.SimpleNamespace: simpler for attribute-only fakes
  • but cannot hold callable methods.

Erros comuns

Forgetting the trailing () to instantiate: type('X', (), {...}) creates a class object, not an instance — calling .save() on the class raises TypeError. Omitting 'self' in the lambda: lambda item: None instead of lambda self, item: None causes TypeError on method call because Python passes the instance as the first argument. Passing the methods dict as the second argument: type('X', {'save': ...}) puts the dict in the bases position, causing TypeError — the empty base-class tuple () is required. Forgetting to quote method keys: {save: ...} instead of {'save': ...} causes NameError since save is not a defined variable.

Similar / contraste

unittest.mock.MagicMock: full-featured mock with call recording and auto-created attributes vs. type() stub which is a minimal silent object. types.SimpleNamespace: attribute-only namespace object vs. type() stub which supports callable methods. collections.namedtuple: immutable tuple with named fields vs. type() stub which is mutable and method-bearing.

Interferências

Coming from JavaScript: may expect object literals like {save: () => null} to create callable objects directly — Python requires explicit class construction via type() or class definitions. Coming from Ruby: may expect OpenStruct or Struct.new to provide similar ad-hoc objects — Python's type() is lower-level and requires manual method definition in a dict.

Família do chunk

  • dynamic class creation
  • test doubles
  • monkey patching
  • type() metaclass construction
  • stub objects

Nuance

Do not use this in production code — it is a testing convenience only; real classes are far more maintainable and discoverable. Each call to type() creates a genuinely new class object in memory, which has minor overhead if used inside tight loops. The lambda methods become true bound methods after instantiation so self is passed automatically, but they lack docstrings, type annotations, and IDE autocompletion support.

Efeito pragmático

Enables rapid test writing by eliminating boilerplate class definitions for simple stubs, keeping test code focused on behavior verification rather than test infrastructure setup.

Dica de memória

type() with three args is Python's class factory — like 3D-printing a disposable object on demand, use it once for a test and throw it away.

Nota

The three-argument form of type() is Python's built-in metaclass constructor — it is exactly what the class statement compiles to under the hood. This pattern leverages that mechanism to skip the class keyword entirely.

Upgrade path

unittest.mock.MagicMock for complex test doubles with behavior verification, or pytest fixtures with proper stub classes for shared test infrastructure

Frequência: LowFormulaicidade: Semi-fixedTipo de construção: dynamic_class_instantiationPrioridade de aquisição: Passive recognitionPrioridade de output: InputTag de espaçamento: Long-termIdioma?: Sim

Log in to save chunks.