Reference Python style guide reverse-engineered from Doguhan Sariturk's (github.com/dogusariturk) real production repositories (HEACalculator, MaterialsFramework, PhaseForgePlus). Use this whenever writing, generating, reviewing, refactoring, or cleaning up ANY Python code for this user — scripts, modules, packages, CLIs, tests, or turning a vibe-coded/notebook-style script into something real — even if the user never mentions style explicitly. Covers project layout (src-layout, uv, ruff, ty, pre-commit, pytest), short single-responsibility files, typing, Google-style docstrings with units and literature references, cached_property for lazy derived attributes, narrow custom exceptions, named unit-conversion constants instead of magic numbers, composition over deep inheritance, registries for optional heavy dependencies, and multiprocessing worker conventions. Where this conflicts with a generic assistant default, this style is correct and the generic default is wrong — apply it before finalizing any Python output for this user. Where it conflicts instead with an established convention already in play for the current codebase (an existing project-scoped skill, or a style already consistently used in the repo being edited), that more specific convention wins on the point of conflict per skill-hierarchy; this skill still governs everywhere that convention doesn't address.
Trending skills
7-day visitors to each skill page
Ships in lps. 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.
This is not a generic style guide. It is reverse-engineered from real, shipped
code — HEACalculator, MaterialsFramework, and PhaseForgePlus by Doguhan
Sariturk (github.com/dogusariturk) — and it is the standard this user wants
applied to their own Python. When any instinct here conflicts with a more
"generic assistant" habit (bare except Exception, numpy-style docstrings,
Optional[X], inline magic numbers, one giant script), this document wins.
Follow it, don't hedge toward the generic habit "for safety."
This authority is over generic defaults, not over a more specific convention.
If the current codebase already has its own established style (a project-scoped
skill, an existing lint config, a pattern used consistently throughout the repo
being edited), that convention is more specific than this one and wins on the
exact point where they disagree — see skill-hierarchy. Everywhere that
convention is silent, this document still applies.
The examples below are written fresh to illustrate each pattern — they are
not copied from his repos. For README / repo-scaffolding concerns (Quick
Start bloat, CITATION.cff, unpinned environments) see the
matsci-python-antipatterns and github-repo-standards skills; this skill
is about the code itself.
Every real project is src-layout, uv-managed, ruff-linted, ty-typed,
and pre-commit-enforced. For anything bigger than a one-off script, scaffold:
project/
├── src/project_name/
│ ├── __init__.py
│ └── ...
├── tests/
│ └── test_*.py
├── pyproject.toml
├── uv.lock
└── .pre-commit-config.yaml
pyproject.toml — adapt, don't paste blindly:
[tool.ruff]
line-length = 130
force-exclude = true
[tool.ruff.lint]
select = ["A", "B", "C4", "D", "E", "ERA", "F", "FA", "I", "ICN", "N", "PL", "PTH", "Q", "SIM", "TC", "UP", "W"]
ignore = ["E501", "PLR0913", "PLR2004"] # long lines and magic-value comparisons are judgment calls, not lint failures
pydocstyle.convention = "google"
[tool.ruff.format]
quote-style = "double"
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
.pre-commit-config.yaml runs, in order: uv lock, ruff check --fix,
ruff format, a type check (ty or mypy), then the standard hygiene hooks
(trailing-whitespace, end-of-file-fixer, check-yaml/toml, check-merge-conflict).
CLIs use typer, not bare argparse. Docs (when the project has them) are
mkdocs-material + mkdocstrings, not a hand-written API reference.
Don't scaffold all of this for a 20-line throwaway script — but even a small script still gets functions, type hints, and a docstring. See §12.
Files are short. This was checked directly: across all three source repos,
counting every non-test, non-__init__.py, non-generated .py file (116
files), the median is ~82 lines, the mean ~188, and three-quarters of
them are under 170 lines. Roughly two-thirds are 100 lines or shorter.
The handful of outliers prove the rule rather than break it. The two files
over 3,000 lines are PyQt GUI pages (parametersPage.py,
batchCalculationsPage.py) — dense widget-wiring code, a different genre
from computational logic — and the one file over 17,000 lines
(HEACalculator_rc.py) is Qt's auto-generated resource-compiler output,
never hand-written and never a model for anything. Excluding those, his
largest genuinely hand-written logic modules — a stability-map calculator,
a thermodynamics module, an MD driver, an elastic-constants module — all land
in the 500–700 line range, and none of his computational code goes higher
than that.
Apply this as a real constraint, not just an aspiration:
utils.py
or helpers.py collecting whatever didn't have an obvious home.*_rc.py, a protobuf stub) isn't part of
this convention at all — it's machine output, not a style to emulate or to
count against a hand-written module's budget.list[str], dict[str, float],
X | None. Never typing.List, typing.Dict, typing.Optional.from __future__ import annotations at the top of any module that has
forward references or wants the modern union syntax guaranteed.if TYPE_CHECKING: — keeps runtime imports light and breaks import cycles:from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from myproject.core.composition import AlloyComposition
class Thermodynamics:
def __init__(self, composition: AlloyComposition) -> None:
self._c = composition
I / isort): stdlib, blank line, third-party, blank
line, local package — always, no manual reordering later.Google convention, always (pydocstyle.convention = "google"). One-line
summary, blank line, then Args: / Returns: / Raises: / Note: /
References: as needed. This applies even to small private (_leading_underscore)
helpers — "it's internal" is not a reason to skip the docstring.
pm, kJ/mol,
eV, K) — in the Returns:/Args: line, not just in a variable name.References: section.r"""...""") for docstrings containing LaTeX/math.def average_radius(fractions: dict[str, float], radii: dict[str, float]) -> float:
"""Composition-weighted average atomic radius.
Args:
fractions (dict[str, float]): Atomic fraction per element symbol.
radii (dict[str, float]): Atomic radius per element symbol, in pm.
Returns:
Composition-weighted average radius in pm.
"""
return sum(frac * radii[elm] for elm, frac in fractions.items())
functools.cached_property for any derived attribute that's expensive
or just non-trivial to compute. Don't compute everything eagerly in
__init__, and don't write a calculate() method that mutates a pile of
instance attributes. Let each property compute itself lazily, once.self._c,
self._t) and calls into it — it doesn't inherit from it or reach into a
God-object.__init__ does the minimum: store what was passed in, validate hard
invariants, nothing else. One-line docstring is fine there; the real
documentation lives on the properties.class SolidSolutionPredictor:
"""Applies formation criteria to an alloy composition.
Args:
composition (AlloyComposition): Parsed alloy composition.
thermodynamics (Thermodynamics): Thermodynamics calculator for the same composition.
"""
def __init__(self, composition: AlloyComposition, thermodynamics: Thermodynamics) -> None:
"""Initialize with a parsed composition and its thermodynamics calculator."""
self._c = composition
self._t = thermodynamics
@cached_property
def microstructure(self) -> str:
"""Expected crystal structure based on VEC.
Returns:
One of "FCC", "BCC", "HCP", or "BCC+FCC".
"""
...
Define narrow, named exceptions subclassing the closest builtin, with
nothing but a one-line docstring — not a bare raise ValueError(...) and not
one giant generic AppError:
class MissingPairDataError(KeyError):
"""Raised when a binary element pair has no entry in a data table."""
class ElementNotFoundError(KeyError):
"""Raised when an element symbol has no entry in the element database."""
Catch narrow-to-broad, most specific first, and when re-raising at a
boundary (e.g. a CLI), chain with from e and add a human-readable message:
except ElementNotFoundError as e:
raise typer.BadParameter(f"Unknown element in '{alloy}': {e}") from e
except Exception as e: # generic fallback, last, still explicit
raise typer.BadParameter(f"Could not process '{alloy}': {e}") from e
Any non-obvious numeric literal — especially a unit conversion — gets a named constant with an inline comment showing the conversion, defined right where it's used (module-level if shared, local if not).
No ALL_CAPS/SCREAMING_SNAKE_CASE globals. Every module-level name,
constants included, stays lowercase snake_case (private ones still get the
leading underscore) — this style never marks a "constant" by shouting its
name in capitals:
_j_per_mol_to_mev_per_atom = 0.0103642688 # 1 J/mol = 0.010364 meV/atom
Module-wide physical constants live once near the top of the module:
gas_constant = 8.314462618 # J / (mol*K)
zip(a, b, strict=True) whenever two sequences are assumed equal length —
catches silent truncation bugs.pathlib.Path, never os.path.return (
"Solid Solution"
if lower_bound < min_formation_enthalpy and max_formation_enthalpy < threshold
else "Multiple Phases"
)
Worker functions passed to ProcessPoolExecutor are:
(result, error_message) tuples instead of letting exceptions
cross the process boundary:def _range_worker(formula: str) -> tuple[list | None, str | None]:
"""Compute results for a single formula.
Intended as a ProcessPoolExecutor worker; imports lazily so worker
processes don't pay import cost they don't need.
Returns:
(result, None) on success, or (None, error_message) on failure.
"""
from myproject.core import Calculator
try:
return Calculator(formula).get_list(), None
except Exception as e:
return None, str(e)
When a package offers many interchangeable backends and each backend has its
own heavy optional dependency (an ML framework, a simulation engine), don't
import them all eagerly. Map name → (module, attr) and resolve lazily via
__getattr__, so import mypackage stays cheap and a user only pays for the
backend they actually use:
_backend_map: dict[str, tuple[str, str]] = {
"FooBackend": ("mypackage.backends.foo", "FooBackend"),
"BarBackend": ("mypackage.backends.bar", "BarBackend"),
}
def __getattr__(name: str) -> type:
"""Lazily import and return a backend class by name."""
if name not in _backend_map:
raise AttributeError(name)
module_name, attr = _backend_map[name]
import importlib
return getattr(importlib.import_module(module_name), attr)
unittest.TestCase-style classes grouped by the function/class under test
(class TestFindAllComps(TestCase):), run through pytest.pytest.approx(...) for any float comparison.class TestAverageRadius(TestCase):
"""Tests for the `average_radius` helper."""
def test_single_element_returns_its_radius(self):
"""A one-element composition returns that element's own radius."""
assert average_radius({"Fe": 1.0}, {"Fe": 126.0}) == pytest.approx(126.0)
When reviewing existing ("vibe-coded") Python against this style, these are the recurring problems to call out and fix:
except: or except Exception: with no narrower exception, no
re-raise, no logging — silently swallowing errors.ALL_CAPS/SCREAMING_SNAKE_CASE module-level constants. Rename to
lowercase snake_case (§7) — this style has no global variables written
in capital letters; "constant-ness" is conveyed by the docstring/comment,
not by shouting the name.Optional[X], List[X], Dict[X, Y] instead of X | None, list[X],
dict[X, Y].self._x
holding a collaborator) would be simpler and more testable.os.path instead of pathlib.Path.utils.py that keeps growing is the classic shape of this.His files carry __author__ / __email__ module headers — that's a
personal-project convention tied to his identity, not a code-quality rule.
Don't stamp his name/email into this user's code. If the user wants an
attribution header pattern, use their name/email; otherwise just skip it.
Run this checklist over what you're about to output:
list[X] / dict[X, Y] / X | None, not typing.List/Optionalcached_property, not eager __init__
work or a mutating calculate() methodValueError/Exception
where the caller might reasonably want to catch a specific failureALL_CAPS/SCREAMING_SNAKE_CASE globals — module-level constants
are lowercase snake_case, private ones with a leading underscorepathlib.Path, zip(..., strict=True)(result, error) tuplesWhat SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
11 skills in this plugin
/adhd-modeFans out several isolated "cognitive-frame" brainstorms on an open-ended problem before switching into a separate critic pass that scores, clusters, flags traps, and deepens only the strongest few — instead of settling for the first plausible answer. Trigger this whenever the user asks to brainstorm, ideate, explore options, says "give me a few ways to...", or explicitly asks for "ADHD mode" / "/adhd" / "divergent mode". Also reach for it proactively on open-ended architecture, API/schema, and naming decisions, product positioning, and fuzzy bugs with no known root cause — anywhere a thoughtful practitioner would say "let me think about this differently for a second." Skip it for lookups, syntax questions, bugs with a known cause, or anywhere the user's phrasing signals they want the quick/standard/canonical answer./full-pathsUse whenever creating, editing, or referencing any file on the user's machine (plots, scripts, data, logs) - always state its complete absolute path, not just a filename, so the user can open or navigate to it directly./github-repo-standardsCreates, scaffolds, and audits GitHub repositories to a professional standard — README, LICENSE, CONTRIBUTING, CODE_OF_CONDUCT, SECURITY.md, issue/PR templates, CI/CD (GitHub Actions), .gitignore, CODEOWNERS, branch protection, semantic versioning, CHANGELOG. Includes a research/academic-software profile (CITATION.cff, Zenodo/DOI citation sections, MkDocs+Material docs, uv/ruff/ty tooling) for lab code, paper companion repos, and other scientific software. Use whenever the user asks to create, scaffold, initialize, structure, clean up, polish, or "make professional" a GitHub repo or open-source project; asks for a README, LICENSE, CONTRIBUTING guide, issue/PR templates, CI setup, a CITATION.cff, or a repo health audit; is preparing a repo for public release, a portfolio, or open-sourcing; or is releasing research/scientific software or anything needing a citation — even if they only mention one piece (e.g. "write me a README") rather than the whole repo./lps-add-skillCreate, import, or update skills in kyryl-shtefiienko/LPS from Claude, choose the common or platform-specific group, and update the README catalog. Use for requests such as add this skill to LPS, turn this workflow into an LPS skill, or update an existing LPS skill. Commit and push only within the user's explicit authorization. Without repository tools, prepare a skill and README change for handoff. Do not use for unrelated repositories or merely executing another skill's workflow./matsci-python-antipatternsChecklist of common bad practices to avoid when writing a README, Quick Start, or repo layout for a materials-science (or other scientific) Python project — bloated "Repository Structure" trees, over-explained Quick Starts, notebook-only packages, unpinned environments, committed data, missing citations. Use this whenever creating, scaffolding, cleaning up, or reviewing a README or repo structure for a materials-informatics, computational-chemistry, DFT, or ML-for-materials Python codebase — even if the user just says "write me a README" or "clean up this repo" without naming these anti-patterns./research-harness-exploreMine the existing research-harness knowledge graph for new research directions by intersecting two or more concept clusters already in the vault (e.g. "Bayesian optimization" and "cold spray additive manufacturing"), proposing candidate research topics, and growing the most promising ones via the existing deepen loop. Use when the user wants to generate research ideas from what's already in their vault, asks "what could I research at the intersection of X and Y", or wants to combine two existing topics into new directions — not for adding papers on a single topic (use research-harness-run for that)./kyryl-shtefiienko-lps:dogusariturk-python-stylefrom lps
Generated from the plugin's indexed repository (kyryl-shtefiienko/lps) — no native marketplace selected
npx claudepluginhub p/kyryl-shtefiienko-lps