ovclash Python Code Style#

This guide applies to every project-owned Python file under ovclash/: the packages under python/, the scripts, tests, benchmarks and samples, the top-level launchers, and the code under tooling/ and tools/. Vendored code (tools/packman/, tools/repoman/) keeps its upstream conventions. A generated file follows its generator; change the generator instead.

The baseline is PEP 8 for code and PEP 257 for docstrings. The rules of this guide supplement both and adapt the applicable rules of the C/C++ code style. Two limits replace the PEP 8 defaults of 79 and 72 columns. Both count indentation:

  • 120 columns for code, including code examples in docstrings;

  • 100 columns for comment and docstring prose.

Rule strength:

  • MUST marks a requirement for every project-owned Python file, not only for new or changed code.

  • SHOULD marks a preference that can yield to a local reason. MAY marks an allowed alternative.

Where this guide is silent, follow the PEPs, then the surrounding code. Keep external API names and serialized field names where compatibility requires them (section 2.2).

1. Files, licensing and organization#

  • Files MUST use UTF-8 and LF line endings; .gitattributes sets eol=lf for *.py. Omit the encoding declaration.

  • A new original file MUST carry the SPDX pair (the two machine-readable license lines of the Software Package Data Exchange standard) that the example of section 1 shows, with its creation year. Preserve existing licenses, attribution and inherited years when you edit, move or derive a file.

  • A file starts with the shebang (executable scripts only), then the license notice, a blank line and the module docstring.

  • A module MUST stay within 100,000 bytes. Split a larger module logically, by responsibility, and keep every existing import path, entry point and test id working:

    • a production module stays at its path as a facade that re-exports every name its importers and patch targets use, or becomes a package of the same import name whose __init__.py re-exports those names and whose __main__.py keeps the python -m entry point;

    • a test module keeps its name for the remaining tests and moves cohesive test cases to new test_<topic>.py modules in the same directory.

  • Do not create trivial modules. Vendored code is never split.

  • Keep the work of an executable script in a main() function behind if __name__ == "__main__":. Importing a module MUST NOT run its command-line workflow.

# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Read and validate saved query settings."""

2. Python layout and names#

2.1 Layout and imports#

The Black code formatter and the isort import sorter own the layout (section 6): indentation, blank lines, wrapping, spacing, string quotes, trailing commas, and import grouping and order. Every file MUST be Black- and isort-clean at 120 columns. Do not hand-format against the tools. A trailing comma keeps a collection or call vertical when that reads better.

  • Prefer absolute imports. Explicit relative imports are acceptable within a package. Do not use wildcard imports.

  • A module MUST import what it uses rather than rely on another module re-exporting it. Keep intended public re-exports explicit.

  • Keep ordinary imports at module scope. A deferred import needs a concrete reason: an optional dependency, expensive initialization or an unavoidable cycle.

  • An optional dependency, such as numpy, warp, pxr or the ovrtx and ovui packages of the ovRTX sample app (a source-only viewer on ovRTX, NVIDIA’s RTX rendering runtime), MUST stay optional for the base library. Import it where the feature needs it and handle its absence there.

  • When import order is load-bearing, such as imports that need an earlier sys.path insertion, put # isort: split before the dependent imports and a comment that says why.

  • Prefer parenthesized continuations to backslashes.

2.2 Names#

  • Functions and methods MUST use snake_case; classes MUST use CapWords. Use snake_case for modules, parameters, variables and attributes, UPPER_SNAKE_CASE for constants, short lowercase names for packages, and a leading underscore for internal details (_name).

  • Do not use the C++ m, g or k prefixes.

  • Prefer descriptive role names: index, item_count, items_by_id, is_valid, has_results. Spell out words and put the verb first in operations, such as collect_overlaps.

A name keeps its external spelling when it must match something outside the project. These are the only exceptions to the casing rules:

Exception

Examples

A test double or helper that mirrors an external API

FakeUi.HStack for omni.ui; GetPrimAtPath on a fake pxr.Usd.Stage; the expect_errors class ported from Kit

A unittest protocol method or hook

setUp, tearDownClass, setUpModule, startTest, addDuration

A ctypes mirror of a C ABI type, and its fields

ovclash_settings_t and its nbTasks field; the Win32 PROCESS_MEMORY_COUNTERS_EX

A shipped public name kept for compatibility

PipelineStepData.mName, Serializer_data_operations

Do not carry an exception’s spelling into new helpers. A custom assertion helper is project code, not part of the unittest protocol: name it assert_rejected, not assertRejected.

3. Docstrings and comments#

3.1 Required docstrings#

A docstring is required (MUST) for:

  • every module, including __init__.py files and test modules;

  • every public class: a class whose name has no leading underscore, defined at module level or inside a public class;

  • every public function and method under the same rule, including test methods, test helpers and the unittest hooks setUp, tearDown, setUpClass, tearDownClass, setUpModule and tearDownModule.

These need no docstring: property setters and deleters, functions and classes nested in a function, _private names and dunder methods. Document a property on its getter. Document constructor arguments in the class docstring, not in __init__.

3.2 Form and content#

  • Use triple double quotes. Use a raw docstring when backslashes must be preserved.

  • Start with a one-line summary that ends in a period. A function summary is an imperative sentence: """Collect overlaps for the selected paths.""". Test methods are the exception (section 3.3). Do not copy the third-person briefs of the C++ convention for Doxygen, the C/C++ documentation generator.

  • A one-line docstring keeps both delimiters on its line. A multi-line docstring has the summary, a blank line and the details, and closes on a line of its own.

  • Separate a class docstring from the first member with a blank line.

  • Document behavior; do not repeat the signature. Where it is not obvious, state the meaning of each parameter, its units, valid range and default, and whether None is accepted. Explain return values, exceptions, side effects and preconditions.

  • For native wrappers, distinguish copied Python values from borrowed native views. Name the owner, what invalidates a view and the required cleanup. Document callback lifetime and threading; do not claim thread safety merely because calls originate in Python.

  • A command-line module that passes description=__doc__ to argparse prints its docstring as --help text. Keep that text accurate for users.

3.3 Docstring templates#

The template depends on whether the docs render the docstring. Sphinx, the documentation generator of the rendered site, reads docstrings through its autodoc extension.

Under python/: Google sections#

Docstrings under python/ use Google-style sections. sphinx.ext.napoleon renders them in the Python API reference, and the docs build treats warnings as errors.

  • Use Args:, Returns: (Yields: for a generator) and Raises:. Add an Example:: literal block only where it helps.

  • Do not write types in the sections; the annotations carry them. Napoleon reads text before a colon in the first line of a Returns: entry as a type.

  • Do not use Attributes: or Methods: sections. Autodoc documents the members itself, and the duplicates fail the build.

  • Put constructor arguments in the Args: section of the class docstring. Sphinx renders the class docstring, not the __init__ one.

  • Document a dataclass field or a class constant with a #: comment above it.

  • Write reStructuredText (reST), not Markdown. Inline code is ``literal``; single backticks and Markdown fences render wrongly.

  • Put *args, **kwargs, glob patterns, |name| and names that end in _ inside double backticks. Bare, they break the build.

  • Put a blank line before and after a list or an indented block. Without it, reST reports an unexpected indentation or unindent, which fails the build.

  • Write a cross-reference role with the full path: :class:`~ovclash.python.suite.types.RunSettings`. A dotted role, such as :class:`.RunSettings`, is ambiguous for a class that both packages define, such as RunSettings or AsyncPipeline, and fails the build.

  • Render the docs to check changed markup; see Building this documentation. The render treats warnings as errors, so a broken docstring fails it with a Sphinx warning that names the docstring (docstring of <object>); fix that docstring and render again.

class SettingsStore:
    """Cache the query settings stored in one JSON file.

    The store hands out copies, so callers never hold a view of its state. Serialize calls that
    share one store.

    Args:
        path: Settings file to open. The file must exist.
        read_only: When True, ``save()`` raises ``RuntimeError`` instead of writing.

    Raises:
        FileNotFoundError: ``path`` does not name a regular file.
    """

    #: File extension of the settings files this class opens.
    EXTENSION = ".json"

    def save(self, query_id: int, settings: dict[str, object], *, overwrite: bool = False) -> bool:
        """Write the settings of one query.

        A failed write leaves the stored settings unchanged.

        Args:
            query_id: Identifier of the query, in the signed 64-bit range.
            settings: Settings keyed by ``SettingId`` name.
            overwrite: Replace existing settings instead of keeping them.

        Returns:
            True when the settings were written; False when the query already has settings and
            ``overwrite`` is False.

        Raises:
            ValueError: ``query_id`` is outside the signed 64-bit range.
            RuntimeError: The store is read-only.
        """

Everywhere else: plain prose#

Benchmarks, scripts, tooling, tools, launchers, samples and tests use plain PEP 257 prose; nothing there is rendered. Name parameters as ``name`` inside sentences and state raised exceptions in prose. Use double backticks for code, not single Markdown backticks.

def shard_count(durations: dict[str, float], budget_seconds: float) -> int:
    """Return the smallest shard count that keeps every shard within ``budget_seconds``.

    A shard that holds a single test may exceed the budget. Raises ``ValueError`` when
    ``budget_seconds`` is not positive.
    """

Tests#

  • A test method docstring is one declarative sentence in the present tense. It states the behavior the test verifies, without “Test that”. It must be true for the test body.

  • A test class docstring is one sentence that names the behavior group.

  • A unittest hook gets one line that says what it prepares or releases.

  • Add a detail paragraph only for a non-obvious fixture or to describe the defect a regression test guards against, without a ticket ID. Verbose unittest output prints the first line.

import unittest


class LoadSettingsTests(unittest.TestCase):
    """Settings files load with overrides applied and reject malformed input."""

    def setUp(self):
        """Create a temporary directory for each test."""

    def test_missing_file_raises_file_not_found(self):
        """A missing settings file raises FileNotFoundError instead of returning defaults."""

3.4 Comments#

  • An implementation comment MUST explain an invariant, a non-obvious decision or a failure being prevented. Do not restate the code.

  • Place # comments above the relevant code at the same indent. Use trailing comments sparingly.

  • Write complete English sentences in impersonal wording, with -- for a dash, as in the C++ prose convention (section 12.2).

  • Do not add author or date stamps, commented-out code or decorative banners.

  • State outstanding work concretely. Do not cite bug-tracker ticket IDs or merge request, CI job or pipeline numbers; explain the behavior instead, as in the C++ convention (section 12.3).

  • Keep identifiers exact and keep comments in step with the behavior.

  • Keep tool directives exactly as written: # noqa, # type: ignore, # pragma: no cover, # isort: split and #:. Write a new suppression for Sonar, the static code analyzer, as # NOSONAR (S5443), with a space before the parenthesis, the bare rule key and a one-line justification in a comment above. Sonar’s Python analyzer does not match a repository-prefixed key such as python:S5443, so a marker written that way suppresses nothing.

4. Types, values and control flow#

4.1 Annotations#

  • Every public non-test function and method MUST be fully annotated. Annotate every parameter except self and cls, and the return type (-> None when it returns nothing). “Public” is defined in section 3.1.

  • Test code is exempt: test_*.py modules and unittest.TestCase subclasses. A helper module under tests/ that is not a test_*.py module is not test code.

  • Other functions MAY be annotated where it clarifies the contract. Avoid redundant annotations on obvious local values.

  • An annotation does not replace runtime validation of untrusted data or of values passed to a native API.

  • In a dataclass or NamedTuple body, an annotated attribute is a field. Annotate a class attribute there only when it is meant to be one; use ClassVar for class-level values.

  • Without from __future__ import annotations, Python evaluates annotations when the def runs. Every annotation name MUST be bound by then; quote a forward reference ("Widget").

  • Do not import an optional dependency at module level only for an annotation. Quote the name or annotate with object.

  • In a module that the Python API reference renders, every annotation MUST resolve through the module’s globals, so that typing.get_type_hints() succeeds. Otherwise Sphinx renders the raw annotation text, which can fail the build.

4.2 Python versions#

  • python/** and the three samples that ship in the wheel (samples/clash_api, samples/clash_suite_api and samples/legacy_clash_detection) MUST run on Python 3.10, the requires-python floor in python/pyproject.toml.

  • Do not use 3.11+ syntax or typing names in that code, such as Self, Never, override or PEP 695 type parameters. Black’s py310 target does not reject them. Compile the files with a 3.10 interpreter to catch newer syntax, and import the modules there to catch newer typing names.

  • A tool or sample with its own documented requirement may use that version.

  • Do not raise the base package’s floor through a style cleanup or an eagerly evaluated annotation.

The ovRTX sample app has such a requirement: it runs on CPython 3.12 (Launching it in the ovRTX Clash Sample App page).

4.3 Values and control flow#

  • Initialize values at first use and keep mutable state in the narrowest useful scope. Prefer instance state to mutable module globals.

  • Named constants SHOULD replace unexplained sentinel values, masks and thresholds.

  • Avoid mutable default arguments and accidental shared class-level containers. Allocate per-call or per-instance state explicitly.

  • Use None for absence only where it cannot be confused with a meaningful value; use a distinct sentinel when the cases must differ. Test None with is and is not, and distinguish absence from an empty container or zero.

  • Prefer early validation and guard returns to deeply nested branches.

  • Iterate over values directly, with enumerate() or zip() when indices or paired values are needed. Use an explicit loop when a comprehension would hide side effects or become hard to read.

  • Keep conditional expressions to simple value choices. Prefer a named function for multi-step or reused behavior; reserve lambdas for small inline callbacks or keys.

  • Production argument validation MUST use explicit checks and exceptions, not assert, which can be disabled. Assertions remain appropriate in tests and for internal debugging invariants.

5. Errors, resources and native boundaries#

5.1 Exceptions#

  • Prefer existing exception types: ValueError for an invalid value, TypeError for an unsuitable type and RuntimeError for a failed native operation. Preserve established exception contracts. Add a new exception class only when callers need to distinguish it.

  • Catch the narrowest useful exception around the smallest fallible operation. Broad catches belong at deliberate reporting, worker, callback or cleanup boundaries. Do not silently turn unexpected failures into empty results or success.

  • Re-raise with bare raise to preserve an exception. To translate one, use raise ... from exception so the cause is kept.

  • Keep the first operational failure primary, and do not report the same error at several layers. Cleanup MUST still run after a failure.

  • Error messages SHOULD follow the C++ wording convention (section 15.3): one present-tense clause, no trailing punctuation, : before detail and ; before a remedy. Name the operation or parameter, and never include secrets.

  • Use the module’s existing diagnostic mechanism. Do not add a competing logging framework or print unsolicited diagnostics from library code.

5.2 Resources and native boundaries#

  • Use context managers for files, locks and native wrappers that support them, or try/finally where no context manager exists. Do not rely on __del__ or garbage-collection timing to release native handles, reports or worker resources. Avoid duplicating cleanup at every early return.

  • Keep owning objects and callback objects alive for every native use, including the encoded bytes that a string helper returns with its C string. Borrowed pointers and buffers MUST NOT outlive their documented owner or survive an invalidating operation.

  • At a C callback boundary, capture Python exceptions and report failure through the documented callback protocol. Never let an exception escape into native code or leave an output marked successful after a failure. Preserve the first failure, and wait for workers before releasing state they may still access.

  • Validate arguments before mutation or resource acquisition, check every native result, and publish outputs only after success. Reuse the binding helpers:

    • both bindings use _uint32_index() from python/ovclash/python/suite/_ctypes_utils.py to reject an index that c_uint32 would truncate;

    • the wrappers of the canonical API, the engine layer, check results with ok() and raise through the _raise_last_error() methods in python/ovclash/python/api/api.py;

    • the binding of the Suite API, the product layer, checks results with _check_result() from _ctypes_utils.py.

  • Keep the canonical and Suite status types apart. bool() of a canonical ovclash_result_t is always true, so if not result: and _check_result() never detect its failure. Test it with ok() from python/ovclash/python/api/_bindings.py, which compares .status with OVCLASH_STATUS_SUCCESS (0). The Suite ovclash_suite_result_t defines __bool__ to compare its status with OVCLASH_SUITE_STATUS_SUCCESS, so if not result: and _check_result() are correct there.

  • Represent text and filesystem paths as str or pathlib.Path, never bytes; public binding path parameters take str. Encode to UTF-8 explicitly at the C boundary where its contract requires it, and never depend on the Windows ANSI code page.

  • Anchor script-owned paths to the script or an explicit root, not to the caller’s working directory. Preserve Windows and Linux behavior and the existing path helpers.

Threading and Ownership and the public-surface rules in AGENTS.md (“Public surfaces, state, and lifetime”) define the runtime contracts; this guide does not change them.

6. Tooling and review#

repo format, a command of the repo tool, runs Black, then isort, on the files that [repo_format.python] in repo.toml selects:

  • Black uses 120 columns and the py310 target from [repo_format.python.black].

  • isort runs with --profile black and reads line_length = 120 and combine_as_imports from .isort.cfg.

  • Neither tool wraps comments or docstrings. Keep prose within 100 columns by hand.

  • Do not run Black or isort with other settings.

Run it from ovclash/, with repo.bat on Windows and ./repo.sh on Linux:

Command

Selects or does

repo.bat format --python-only <files>

Formats the named files.

repo.bat format --python-only --modified

Formats the files with uncommitted changes.

repo.bat format --python-only --since origin/trunk

Formats the files changed on this branch since it left trunk; run git fetch origin trunk first. When the fetch fails, check the network and your access to the remote; an outdated origin/trunk selects files that other branches changed.

--list, added to any of these

Prints the selected files without formatting them.

--verify, added to any of these

Checks formatting and license headers without writing.

Each command exits with code 0 on success. A --verify run exits with a nonzero code when a selected file is not formatted or its header differs, and names each such file.

A run that writes files also normalizes license headers:

  • It adds the SPDX pair to a file without a copyright notice.

  • It rewrites an NVIDIA notice into that pair. It keeps the start year, sets the end year to the current year and drops a different license, such as LicenseRef-NvidiaProprietary, with its text.

  • It leaves another owner’s notice unchanged and prints a warning.

Do not run repo format on a file whose existing notice must be kept (section 1). List such a file in the exclude list of [repo_format.python] in repo.toml:

Field

Type

Required

Default or values

Description

files.exclude."++"

TOML array of strings, each a glob pattern relative to ovclash/

No

Appended to the inherited exclude list. It already holds "tools/packman/**", "tools/repoman/**", the build and install outputs, the virtual environments and the generated API pages

The files that repo format never selects through files.include.

File arguments, --modified and --since ignore that exclude list, so they still select the file.

CI checks only license headers; see License headers. No CI job runs Black or isort, so format every Python file you change before review. Run the checks that Required validation lists for the affected surface.

No tool checks the docstring, annotation, naming and module-size rules as a whole; reviewers do. Two checks cover part of them:

  • The docs render, which runs in CI, fails on broken markup in a rendered docstring.

  • tests/python_tests/test_runtime.py evaluates every function annotation of both _bindings modules.

Before submitting Python changes, check that:

  • [ ] Licensing and attribution are preserved; a new original file has the SPDX pair.

  • [ ] Every changed file is Black- and isort-clean, prose fits 100 columns and no module exceeds 100,000 bytes.

  • [ ] Every module, public class and public function or method has a docstring in the template of its area (section 3).

  • [ ] Every public non-test function and method is fully annotated, and the code respects the minimum Python version (section 4).

  • [ ] Names follow section 2.2.

  • [ ] Validation, error propagation and deterministic cleanup preserve the API contract.

  • [ ] Tests and documentation reflect the behavior.