Kaili Cao 曹开力

Opinions · My Python Style

My Python Style

How I organize and write research code, so that a collaborator can read it, rerun it and extend it without asking me.

Python Philosophy is about how to think about code; this page is about how my own code looks. It describes habits, not rules: take what helps, and in someone else's repository, follow the style it already has. The examples come from repositories I wrote or helped write: Effortless (fast linear image reconstruction for Roman), PyIMCOM (its predecessor, whose refactoring I led), mesa_apokasc (stellar models of red giants) and ContEvol (a numerical method for differential equations).

How a project is laid out

Code a reader can follow

Figures from code

Commits that explain

With an AI assistant

An assistant may write the code, but a person must be able to read, check and explain every line of it (Python Philosophy).

Habits I keep

A few of my habits depart from the most common Python style: short statements share a line when they read as one thought (if not mask_out[i]: continue); a class runs its stages through __call__; and flags in exploratory notebooks carry the date they were set. When I contribute to someone else's code, I follow its style, and I never mix a change of style into a commit that changes behavior.

Some habits suit a prototype better than a shared code. As a code gains users, it gains what they need: a package they can install, tests that run on every change, and log messages instead of printed ones.