Quick reference for Java/GoF patterns (Singleton, Abstract Factory, Factory Method) that add ceremony in Python, with Pythonic alternatives and links to detailed skills.
Ships in pystack-python. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
The GoF book was written for C++ and Java in 1994. Some of its patterns address language constraints those languages had (no first-class functions, no modules-as-namespaces, mandatory new) that Python doesn't. Agents still import those shapes into Python, usually as ceremony.
This is the quick reference for the imported patterns that show up in real Python reviews. It is not a GoF encyclopedia.
Symptom: class Logger: _instance = None; def __new__(cls): if cls._instance is None: ...; or Logger.instance() as the canonical accessor; or @singleton decorator.
Why it fights Python: Python has modules. A module is loaded once. A module-level variable IS a singleton. There's no new keyword to prevent — there's just construction, which you can choose not to do.
For services with app-lifetime state (DB pool, HTTP client), use dependency injection — create once in lifespan, store on app.state, inject through Depends. Singletons hide their dependencies; DI makes them explicit and testable.
Use instead:
python-fastapi-sa-app-setup)# Don't
class StripeClient:
_instance: "StripeClient | None" = None
@classmethod
def instance(cls) -> "StripeClient":
if cls._instance is None:
cls._instance = cls(...)
return cls._instance
# Do — init in lifespan, inject via Depends
async def init_stripe_client(app: FastAPI, config: StripeConfig) -> None:
app.state.stripe_client = StripeClient(...)
def get_stripe_client(request: Request) -> StripeClient:
return request.app.state.stripe_client
See: python-fastapi-sa-app-setup, python-external-client
Symptom: class AbstractEmailClientFactory: @abstractmethod def create(...); concrete factory subclasses for each "family" of products.
Why it fights Python: Classes are first-class objects — you can pass the class itself, or store classes in a dict, and the dispatch becomes a one-line lookup. No AbstractFactory → ConcreteFactory → Product hierarchy needed.
Use instead:
# Don't — Java-shaped AbstractFactory + ConcreteFactory hierarchy
class AbstractEmailClientFactory(ABC):
@abstractmethod
def create_client(self, config: EmailConfig) -> EmailClient: ...
class SendGridClientFactory(AbstractEmailClientFactory):
def create_client(self, config: EmailConfig) -> EmailClient:
return SendGridClient(config)
# Do — dict dispatch. Classes ARE first-class objects in Python; store them.
_EMAIL_CLIENTS: dict[str, type[EmailClient]] = {
"sendgrid": SendGridClient,
"postmark": PostmarkClient,
"ses": SESClient,
}
def make_email_client(config: EmailConfig) -> EmailClient:
try:
return _EMAIL_CLIENTS[config.provider](config)
except KeyError:
raise ValueError(f"unknown email provider: {config.provider}")
Adding a new provider is one entry in the dict, not a new if branch.
For closed sets where you want exhaustiveness checking from ty, match-case also works:
def make_email_client(config: EmailConfig) -> EmailClient:
match config.provider:
case "sendgrid": return SendGridClient(config)
case "postmark": return PostmarkClient(config)
case "ses": return SESClient(config)
case other: raise ValueError(f"unknown email provider: {other}")
Use dict for open sets (plugin-style; consumers register their own). Use match for closed sets (fixed list). Avoid if/elif chains — they don't scale and aren't idiomatic.
See: python-typing-idioms, python-fastapi-sa-app-setup
@classmethod returning SelfSymptom: Subclasses override a _create() method to choose what to construct.
Why it fights Python: Subclasses can override __init__ directly, or you can use a @classmethod returning Self to allow per-subclass construction logic. Either way is simpler than the GoF subclass-dance.
Use instead:
@classmethod from_X(cls, ...) -> Self for alternative constructors__init__ overrides for variantsclass OrderGet(BaseModel):
@classmethod
def from_model(cls, order: Order) -> Self:
return cls.model_validate(order)
@classmethod
def from_openai(cls, payload: dict) -> Self:
return cls(id=..., customer_id=...)
See: python-typing-idioms, python-service-and-schema-cohesion
These verdicts assume Python. In a polyglot codebase that ports patterns from other languages, some of these can be the right call for consistency. The verdict here is "usually ceremony when starting fresh in Python."
A few specific exceptions:
__new__ trick works. Almost always a smell, but not always wrong.from_<source> constructors or a plain factory function.python-typing-idioms — Protocol, Self, alternative constructors via classmethodpython-fastapi-sa-app-setup — Singleton redirect (DI)python-stdlib-idioms — when GoF Composite or Iterator is the right shape (Protocol + dataclass for trees; generators for iteration)What SKILL.md sets; muted values are Claude Code's defaults
/pystack-python:python-antipatterns-cheatsheetfrom pystack-python
npx claudepluginhub denyszhak/pystack-skills --plugin pystack-python4 skills in this plugin
/python-stdlib-idiomsUse when iterating over collections, building lazy pipelines, or modeling tree /
recursive structures (filesystems, ASTs, query builders, UI trees). Triggers on
imports of `itertools`, `collections.abc`; on `for ... yield ...`, `__iter__`,
generators; on tree-shaped data, leaf/composite distinctions, recursive
traversal. Encodes: generators over hand-rolled iterators, `itertools` for
composition, `AsyncIterator[T]` for async, closed unions + dataclasses for
tree shapes, recursive generators for traversal, exhaustive `match` for
visitor dispatch.
Do NOT use for: type-system idioms (use python-typing-idioms); domain
primitives (use python-value-objects); aggregates (use python-aggregate-and-repo).
/python-typing-idiomsUse when writing or modifying typed Python code (any project — libraries, services,
scripts). Triggers on `.py` files with type annotations; on imports from `typing`,
`typing_extensions`, `collections.abc`; on user questions about type hints,
Protocol, generics, NewType, PEP 695. Encodes: Protocol over ABC for ports,
`Self` for classmethod constructors, `NewType` for ID safety, PEP 695 type
aliases and generics, `Annotated` for FastAPI/Pydantic metadata, alternative
constructors via `@classmethod from_X(cls, ...) -> Self`, avoiding `Any`,
narrowing patterns.
Do NOT use for: untyped Python codebases that aren't ready to adopt type hints.
Other plugins' skills for the same job