Python Guru
Enforce modern, idiomatic Python 3.12+ across every task. Never suggest deprecated patterns, legacy tooling, or outdated idioms. When in doubt, check the reference files before answering.
When to Use
- Writing new Python code of any kind
- Reviewing or refactoring existing Python code
- Setting up a new Python project (structure, tooling, CI)
- Debugging Python errors or unexpected behaviour
- Advising on async, typing, testing, or performance
- User asks: "is this Pythonic?", "how do I do X in Python?", "review my code"
When NOT to Use
- Pure architecture discussions with no Python specifics
- Non-Python languages (even in mixed-language repos)
- System administration tasks where Python is incidental
Enforcement Checklist
Run through this for every block of Python code you write or review:
Tooling
-
uvused for package/project management; nopip installdirectives in docs -
ruffconfigured inpyproject.tomlwithUP,B,SIM,TCH,Srules enabled -
pyright(not mypy) as primary type checker;typeCheckingMode = "standard"minimum - All config in
pyproject.toml; nosetup.py,setup.cfg,.flake8,mypy.ini -
requires-python = ">=3.12"set
Types
-
X | Noneinstead ofOptional[X] -
list[int]/dict[str, int]instead ofList[int]/Dict[str, int] -
[T]inline syntax (PEP 695) instead ofT = TypeVar("T")for 3.12+ targets -
type Alias = ...statement instead ofTypeAliasannotation -
@overrideon every method that intentionally overrides a parent method -
Selffor fluent/builder return types -
Protocolpreferred overABCfor structural interfaces -
@dataclass(slots=True, frozen=True)for value objects -
if TYPE_CHECKING:block for import-time-only type references
Async
-
asyncio.TaskGroupinstead ofasyncio.gather()for structured concurrency -
asyncio.timeout()context manager instead ofasyncio.wait_for() -
asyncio.get_running_loop()inside coroutines (neverget_event_loop()) -
CancelledErroralways re-raised after cleanup - Blocking calls wrapped in
asyncio.to_thread()
Testing
-
pytestwith@pytest.mark.parametrize; nounittest.TestCase - Hypothesis
@givenfor pure functions that accept unconstrained input - Fixtures use
yieldwith teardown; scoped appropriately - Tests outside
src/;tmp_pathfor filesystem; no real network in unit tests -
branch = truein coverage;fail_under = 90
Security
- Parameterised queries. Never f-strings into SQL
-
secretsmodule for tokens/passwords. Neverrandom -
subprocess.run(["cmd", arg], ...). Nevershell=Truewith user input - No
eval()orexec()on external input -
LiteralStringannotations on functions that accept SQL/HTML/shell fragments - Secrets sourced from environment variables. Never hardcoded
-
secrets.compare_digest()for token comparison
Common Anti-Patterns (instant fail)
- No mutable default arguments (
def f(x=[])) - No bare
except:. Always at leastexcept Exception: - No
type(x) is Foo. Useisinstance(x, Foo) - No
datetime.utcnow(). Usedatetime.now(UTC) - No string concatenation in loops. Use
str.join() - No
os.path.join(). Usepathlib.Path - No silent exception swallowing: log and re-raise, or use
suppress()explicitly - No root logger (
logging.getLogger()). Alwayslogging.getLogger(__name__) - No f-strings in log calls. Use
%-style lazy formatting
Quick-Reference: Old → New
| Old (pre-2024) | New (2026) |
|---|---|
pip + virtualenv + pyenv | uv |
black + isort + flake8 | ruff format + ruff check |
TypeVar("T") | [T] inline type parameter |
Optional[X] | X | None |
Union[A, B] | A | B |
Dict[str, int], List[int] | dict[str, int], list[int] |
TypeAlias annotation | type Alias = ... statement |
asyncio.gather() | asyncio.TaskGroup |
asyncio.wait_for() | asyncio.timeout() |
datetime.utcnow() | datetime.now(UTC) |
setup.py / setup.cfg | pyproject.toml only |
ABC for interfaces | Protocol |
@dataclass | @dataclass(slots=True) |
Project Bootstrap
For a new Python project, create this structure immediately:
my-project/
├── src/
│ └── my_package/
│ ├── __init__.py # define __all__
│ └── ...
├── tests/
│ ├── conftest.py
│ └── test_*.py
├── pyproject.toml
├── uv.lock # commit for apps; gitignore for libraries
└── mise.toml # optional but recommended
Bootstrap commands:
uv init my-project --lib # src layout, pyproject.toml
cd my-project
uv add --dev pytest ruff pyright hypothesis
Minimal pyproject.toml:
[project]
requires-python = ">=3.12"
[tool.ruff]
target-version = "py312"
[tool.ruff.lint]
select = ["E","W","F","I","B","C4","UP","SIM","TCH","RUF","PT","S","ANN"]
ignore = ["ANN101","ANN102","ANN401"]
[tool.pyright]
pythonVersion = "3.12"
typeCheckingMode = "standard"
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "--strict-markers -q"
[tool.coverage.run]
source = ["src"]
branch = true
[tool.coverage.report]
fail_under = 90
References
Load these files when you need depth beyond this overview:
references/tooling.md: uv, ruff, pyright, mise configuration + CI setupreferences/type-system.md: full type annotation guide, PEP 695, Protocol, TypedDictreferences/async.md: async patterns, TaskGroup, pitfalls, anyioreferences/testing.md: pytest fixtures, Hypothesis strategies, coveragereferences/security.md: injection prevention, secrets, subprocess safety, t-stringsreferences/anti-patterns.md: full anti-pattern catalogue with fixes