Python Code Guidelines

Based on the Google Python Style Guide with modifications for our conventions.

1 Python Language Rules

1.1 Linting and Type Checking

We use Ruff for linting, and ty + Pyright for type checking. All code must pass all checks before being committed.

1.1.1 Definition

  • Ruff: A fast Python linter that combines multiple tools (pycodestyle, Pyflakes, flake8-bugbear, isort, and more) into a single, extremely fast linter.
  • ty: A gradual type checker that focuses on return types and argument types, providing more precise type checking than Pyright alone.
  • Pyright: A static type checker for Python that validates type annotations and catches structural type errors (invalid type arguments, call issues).

1.1.2 Running Linting and Type Checking

Lint all Python services:

task python:lint

This runs Ruff on all services in services/py/ (except hidden directories and test directories).

Type check all Python services:

task python:typecheck

This runs both ty and pyright on all services in services/py/.

Manual commands for a specific service:

cd services/py/<service-name>

# Lint
uv run ruff check .

# Auto-fix linting issues
uv run ruff check --fix .

# Type check with ty
uv run ty check

# Type check with pyright
uv run pyright

1.1.3 Linting Configuration

Our Ruff configuration is in services/py/ruff.toml and includes:

  • Line length: 120 characters
  • Enabled rule sets: pycodestyle (E), Pyflakes (F), flake8-bugbear (B), flake8-simplify (SIM), isort (I), eradicate (ERA), flake8-annotations (ANN), flake8-bandit (S), flake8-boolean-trap (FBT), flake8-builtins (A), flake8-pie (PIE), flake8-print (T20), flake8-return (RET), flake8-self (SLF), flake8-unused-arguments (ARG), NumPy-specific rules (NPY), pandas-vet (PD), pep8-naming (N), and pylint (PLC, PLE, PLW)
  • Globally ignored rules: S101, ANN204, B007, ANN002, ANN003, N818, FBT001, SIM112, ANN401, SIM117, S311, S113, B008

Each service extends this base configuration via pyproject.toml:

[tool.ruff]
extend = "../ruff.toml"

1.1.4 Type Checking Configuration

ty Configuration:

ty is configured per-service in pyproject.toml:

[tool.ty.environment]
extra-paths = ["../common", "../other_dependency"]

ty focuses on checking:

  • Return types
  • Argument types
  • Precise type inference

Pyright Configuration:

Our Pyright configuration is in services/py/pyright.toml with conservative settings that focus on critical type errors while letting ty handle return types and argument types:

  • reportInvalidTypeArguments = true: Catch invalid type arguments
  • reportCallIssue = true: Catch call-related issues
  • reportReturnType = false: Let ty handle this
  • reportArgumentType = false: Let ty handle this
  • reportAttributeAccessIssue = false: Too noisy
  • reportIncompatibleMethodOverride = false: Too noisy
  • reportAssignmentType = false: Let ty handle this

Each service extends this base configuration via pyproject.toml:

[tool.pyright]
extends = "../pyright.toml"
extraPaths = ["../common", "../other_dependency"]

1.1.5 Suppressing Warnings

IMPORTANT: Only suppress warnings using comments in the file. Never add ignores to pyproject.toml except for the tests/* directory.

Per-line suppression (use sparingly):

# Suppress a specific Ruff rule on the next line
result = eval(user_input)  # noqa: S307

# Suppress multiple rules
value = some_function()  # noqa: ARG001, ANN201

File-level suppression (add at the top of the file):

# ruff: noqa: S311, S113
"""Module that needs to ignore specific security warnings."""

ty suppression:

# Suppress ty type checking for a single line
result = some_function()  # ty: ignore

# File-level ty ignore (add at top of file after imports)
# ty: ignore

Pyright suppression:

# Suppress type checking for a single line
result = some_function()  # type: ignore

# Suppress with a specific error code
result = some_function()  # type: ignore[return-value]

# File-level pyright ignore (add at top of file)
# pyright: reportAttributeAccessIssue=false

Note: Prefer fixing type issues over suppressing them. Use ty and pyright suppressions sparingly and only when absolutely necessary.

1.1.6 Per-File Ignores in pyproject.toml

The ONLY acceptable use of per-file ignores in pyproject.toml is for the tests directory:

[tool.ruff.lint.per-file-ignores]
"tests/*" = ["SLF001"]  # Allow accessing private members in tests

For all other suppressions, use comments in the code as shown above.

1.1.7 Best Practices

  • Fix, don’t suppress: Try to fix the issue rather than suppress the warning.
  • Add explanations: When you must suppress a warning, add a comment explaining why.
  • Be specific: Use specific error codes rather than blanket noqa or type: ignore.
  • Keep suppressions local: Suppress at the line level, not file level, whenever possible.
  • Review regularly: Suppressions should be temporary solutions, not permanent fixes.

1.2 Imports

You can import packages, modules, classes, functions, and other objects directly. However, never use wildcard imports (from x import *).

1.2.1 Definition

Reusability mechanism for sharing code from one module to another.

1.2.2 Pros

  • Importing specific objects makes it clear what is being used in the code.
  • Helps avoid namespace pollution and makes dependencies explicit.
  • Shorter names in the code when importing objects directly.

1.2.3 Cons

  • Import statements can become long if many objects are imported.
  • Potential for name collisions if not managed carefully.

1.2.4 Decision

Absolute imports only: Always use absolute imports. Relative imports are forbidden, even within the same package. This prevents confusion and ensures clarity about where imports come from.

# Good: Absolute import
from myproject.backend.services import UserService

# Bad: Relative import
from ..services import UserService  # Never do this!
from .utils import helper  # Never do this!

Import what you need:

  • You can import modules: import os, import sys
  • You can import specific objects: from myproject.services import UserService, OrderService
  • You can import classes: from myproject.models import User
  • You can import functions: from myproject.utils import parse_date
  • You can use aliases for clarity: from myproject.services import UserService as US

Never use wildcard imports:

# Bad: Wildcard import
from myproject.services import *  # Never do this!

Example of proper imports:

# Import modules
import os
import sys

# Import specific objects, classes, or functions
from typing import Optional, List
from myproject.backend.services import UserService, OrderService
from myproject.backend.models import User, Order
from myproject.backend.utils import parse_date, format_currency

# Use aliases when needed for clarity
from myproject.backend.services.external import APIClient as ExternalAPIClient

Use the full package path: Always use the full package path in imports to make it clear where the import comes from and to avoid accidentally importing a package twice.

1.2.4.1 Exemptions

Exemptions from this rule:

1.3 Packages

Import each module using the full pathname location of the module.

1.3.1 Pros

Avoids conflicts in module names or incorrect imports due to the module search path not being what the author expected. Makes it easier to find modules.

1.3.2 Cons

Makes it harder to deploy code because you have to replicate the package hierarchy. Not really a problem with modern deployment mechanisms.

1.3.3 Decision

All new code should import each module by its full package name.

Imports should be as follows:

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)

(assume this file lives in doctor/who/ where jodie.py also exists)

No:
  # Unclear what module the author wanted and what will be imported.  The actual
  # import behavior depends on external factors controlling sys.path.
  # Which possible jodie module did the author intend to import?
  import jodie

The directory the main binary is located in should not be assumed to be in sys.path despite that happening in some environments. This being the case, code should assume that import jodie refers to a third-party or top-level package named jodie, not a local jodie.py.

1.4 Exceptions

Exceptions are a powerful tool for error handling, but they should be used strategically. Let exceptions bubble up to where they can be properly handled.

1.4.1 Definition

Exceptions are a means of breaking out of normal control flow to handle errors or other exceptional conditions.

1.4.2 Pros

The control flow of normal operation code is not cluttered by error-handling code. It also allows the control flow to skip multiple frames when a certain condition occurs, e.g., returning from N nested functions in one step instead of having to plumb error codes through.

1.4.3 Cons

May cause the control flow to be confusing. Easy to miss error cases when making library calls. Overuse of try/except can hide bugs and make debugging harder.

1.4.4 Decision

Always use specific exception types:

Use built-in exception classes (ValueError, TypeError, RuntimeError, etc.) or define custom exceptions. Never raise bare Exception.

Yes:
  def process_user_age(age: str) -> int:
    """Process and validate user age.

    Raises:
      ValueError: If age is not a valid positive integer.
    """
    try:
      age_int = int(age)
    except ValueError as e:
      raise ValueError(f"Age must be a valid integer, got: {age}") from e

    if age_int < 0:
      raise ValueError(f"Age must be positive, got: {age_int}")

    return age_int

No:
  def process_user_age(age: str) -> int:
    try:
      age_int = int(age)
    except Exception:
      raise Exception("Invalid age")  # Non-specific exception

    return age_int

Don’t wrap everything in try/except:

Only use try/except where you have a specific reason to handle an exception. Let other exceptions propagate naturally.

Yes:
  def calculate_average(numbers: list[float]) -> float:
    """Calculate average. Let ZeroDivisionError propagate if list is empty."""
    return sum(numbers) / len(numbers)

No:
  def calculate_average(numbers: list[float]) -> float:
    try:
      return sum(numbers) / len(numbers)
    except Exception as e:
      # Pointless wrapping - just let it fail!
      raise

Don’t catch, log, and re-raise:

If you can’t handle an exception meaningfully, don’t catch it. Let it bubble up to where it can be properly handled (usually at the top level).

Yes:
  def read_config_file(path: str) -> dict:
    """Read config file. Let exceptions propagate to caller."""
    with open(path) as f:
      return json.load(f)

No:
  def read_config_file(path: str) -> dict:
    try:
      with open(path) as f:
        return json.load(f)
    except Exception as e:
      logger.error(f"Failed to read config: {e}")
      raise  # Just adds noise to the stack trace!

Use contextlib.suppress instead of try/pass:

Never use try/except with an empty pass block. Use contextlib.suppress to make the intent explicit.

Yes:
  from contextlib import suppress

  # Explicitly suppress specific exceptions
  with suppress(FileNotFoundError):
    os.remove(temp_file)

No:
  try:
    os.remove(temp_file)
  except FileNotFoundError:
    pass  # Silent failures are hard to debug

Catch exceptions at the top level or with specific intent:

Exception handling should happen at architectural boundaries (API endpoints, CLI entry points, worker tasks) or when you have specific recovery logic.

Yes:
  # In a gRPC service handler (top level)
  def GetUser(self, request, context):
    try:
      user = self.user_service.get_user(request.user_id)
      return user_pb2.User(...)
    except UserNotFoundError as e:
      context.set_code(grpc.StatusCode.NOT_FOUND)
      context.set_details(str(e))
      return user_pb2.User()
    except ValueError as e:
      context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
      context.set_details(str(e))
      return user_pb2.User()

Yes:
  # With specific recovery intent
  def get_cached_or_fetch(key: str) -> dict:
    try:
      return cache.get(key)
    except CacheExpiredError:
      # Specific recovery: fetch fresh data
      return fetch_from_database(key)

No:
  # In a service method (too low level)
  def get_user(self, user_id: str) -> User:
    try:
      return self.repository.find_by_id(user_id)
    except Exception as e:
      # Wrong place to catch! Let it propagate up.
      logger.error(f"Error getting user: {e}")
      raise

Custom exceptions:

When defining custom exceptions, inherit from appropriate base classes and ensure names end with Error or Exception.

Yes:
  class UserNotFoundError(ValueError):
    """Raised when a user cannot be found."""
    pass

  class ConfigurationError(RuntimeError):
    """Raised when configuration is invalid."""
    pass

No:
  class UserNotFound(Exception):  # Should end with 'Error'
    pass

  class MyException(Exception):  # Too generic name
    pass

Assert statements:

Do not use assert for input validation or business logic. Use assert only for invariants and conditions that should never happen in correct code. assert statements can be disabled with Python’s -O flag.

Yes:
  def process_user(user_id: str) -> User:
    if not user_id:
      raise ValueError("user_id cannot be empty")

    user = fetch_user(user_id)
    assert user.id == user_id  # Invariant check, safe to remove
    return user

No:
  def process_user(user_id: str) -> User:
    assert user_id, "user_id required"  # Wrong! Use ValueError instead
    return fetch_user(user_id)

1.5 Mutable Global State

Avoid mutable global state.

1.5.1 Definition

Module-level values or class attributes that can get mutated during program execution.

1.5.2 Pros

Occasionally useful.

1.5.3 Cons

  • Breaks encapsulation: Such design can make it hard to achieve valid objectives. For example, if global state is used to manage a database connection, then connecting to two different databases at the same time (such as for computing differences during a migration) becomes difficult. Similar problems easily arise with global registries.
  • Has the potential to change module behavior during the import, because assignments to global variables are done when the module is first imported.

1.5.4 Decision

Avoid mutable global state.

In those rare cases where using global state is warranted, mutable global entities should be declared at the module level or as a class attribute and made internal by prepending an _ to the name. If necessary, external access to mutable global state must be done through public functions or class methods. See Naming below. Please explain the design reasons why mutable global state is being used in a comment or a doc linked to from a comment.

Module-level constants are permitted and encouraged. For example: _MAX_HOLY_HANDGRENADE_COUNT = 3 for an internal use constant or SIR_LANCELOTS_FAVORITE_COLOR = "blue" for a public API constant. Constants must be named using all caps with underscores. See Naming below.

1.6 Nested/Local/Inner Classes and Functions

Nested local functions or classes are fine when used to close over a local variable. Inner classes are fine.

1.6.1 Definition

A class can be defined inside of a method, function, or class. A function can be defined inside a method or function. Nested functions have read-only access to variables defined in enclosing scopes.

1.6.2 Pros

Allows definition of utility classes and functions that are only used inside of a very limited scope. Very ADT-y. Commonly used for implementing decorators.

1.6.3 Cons

Nested functions and classes cannot be directly tested. Nesting can make the outer function longer and less readable.

1.6.4 Decision

They are fine with some caveats. Avoid nested functions or classes except when closing over a local value other than self or cls. Do not nest a function just to hide it from users of a module. Instead, prefix its name with an _ at the module level so that it can still be accessed by tests.

1.7 Comprehensions & Generator Expressions

Okay to use for simple cases.

1.7.1 Definition

List, Dict, and Set comprehensions as well as generator expressions provide a concise and efficient way to create container types and iterators without resorting to the use of traditional loops, map(), filter(), or lambda.

1.7.2 Pros

Simple comprehensions can be clearer and simpler than other dict, list, or set creation techniques. Generator expressions can be very efficient, since they avoid the creation of a list entirely.

1.7.3 Cons

Complicated comprehensions or generator expressions can be hard to read.

1.7.4 Decision

Comprehensions are allowed, however multiple for clauses or filter expressions are not permitted. Optimize for readability, not conciseness.

Yes:
  result = [mapping_expr for value in iterable if filter_expr]

  result = [
      is_valid(metric={'key': value})
      for value in interesting_iterable
      if a_longer_filter_expression(value)
  ]

  descriptive_name = [
      transform({'key': key, 'value': value}, color='black')
      for key, value in generate_iterable(some_input)
      if complicated_condition_is_met(key, value)
  ]

  result = []
  for x in range(10):
    for y in range(5):
      if x * y > 10:
        result.append((x, y))

  return {
      x: complicated_transform(x)
      for x in long_generator_function(parameter)
      if x is not None
  }

  return (x**2 for x in range(10))

  unique_names = {user.name for user in users if user is not None}
No:
  result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]

  return (
      (x, y, z)
      for x in range(5)
      for y in range(5)
      if x != y
      for z in range(5)
      if y != z
  )

1.8 Default Iterators and Operators

Use default iterators and operators for types that support them, like lists, dictionaries, and files.

1.8.1 Definition

Container types, like dictionaries and lists, define default iterators and membership test operators (“in” and “not in”).

1.8.2 Pros

The default iterators and operators are simple and efficient. They express the operation directly, without extra method calls. A function that uses default operators is generic. It can be used with any type that supports the operation.

1.8.3 Cons

You can’t tell the type of objects by reading the method names (unless the variable has type annotations). This is also an advantage.

1.8.4 Decision

Use default iterators and operators for types that support them, like lists, dictionaries, and files. The built-in types define iterator methods, too. Prefer these methods to methods that return lists, except that you should not mutate a container while iterating over it.

Yes:  for key in adict: ...
      if obj in alist: ...
      for line in afile: ...
      for k, v in adict.items(): ...
No:   for key in adict.keys(): ...
      for line in afile.readlines(): ...

1.9 Generators

Use generators as needed.

1.9.1 Definition

A generator function returns an iterator that yields a value each time it executes a yield statement. After it yields a value, the runtime state of the generator function is suspended until the next value is needed.

1.9.2 Pros

Simpler code, because the state of local variables and control flow are preserved for each call. A generator uses less memory than a function that creates an entire list of values at once.

1.9.3 Cons

Local variables in the generator will not be garbage collected until the generator is either consumed to exhaustion or itself garbage collected.

1.9.4 Decision

Fine. Use “Yields:” rather than “Returns:” in the docstring for generator functions.

If the generator manages an expensive resource, make sure to force the clean up.

A good way to do the clean up is by wrapping the generator with a context manager PEP-0533.

1.10 Lambda Functions

Okay for one-liners. Prefer generator expressions over map() or filter() with a lambda.

1.10.1 Definition

Lambdas define anonymous functions in an expression, as opposed to a statement.

1.10.2 Pros

Convenient.

1.10.3 Cons

Harder to read and debug than local functions. The lack of names means stack traces are more difficult to understand. Expressiveness is limited because the function may only contain an expression.

1.10.4 Decision

Lambdas are allowed. If the code inside the lambda function spans multiple lines or is longer than 60-80 chars, it might be better to define it as a regular nested function.

For common operations like multiplication, use the functions from the operator module instead of lambda functions. For example, prefer operator.mul to lambda x, y: x * y.

1.11 Conditional Expressions

Okay for simple cases.

1.11.1 Definition

Conditional expressions (sometimes called a “ternary operator”) are mechanisms that provide a shorter syntax for if statements. For example: x = 1 if cond else 2.

1.11.2 Pros

Shorter and more convenient than an if statement.

1.11.3 Cons

May be harder to read than an if statement. The condition may be difficult to locate if the expression is long.

1.11.4 Decision

Okay to use for simple cases. Each portion must fit on one line: true-expression, if-expression, else-expression. Use a complete if statement when things get more complicated.

Yes:
    one_line = 'yes' if predicate(value) else 'no'
    slightly_split = ('yes' if predicate(value)
                      else 'no, nein, nyet')
    the_longest_ternary_style_that_can_be_done = (
        'yes, true, affirmative, confirmed, correct'
        if predicate(value)
        else 'no, false, negative, nay')
No:
    bad_line_breaking = ('yes' if predicate(value) else
                         'no')
    portion_too_long = ('yes'
                        if some_long_module.some_long_predicate_function(
                            really_long_variable_name)
                        else 'no, false, negative, nay')

1.12 Default Argument Values

Okay in most cases.

1.12.1 Definition

You can specify values for variables at the end of a function’s parameter list, e.g., def foo(a, b=0):. If foo is called with only one argument, b is set to 0. If it is called with two arguments, b has the value of the second argument.

1.12.2 Pros

Often you have a function that uses lots of default values, but on rare occasions you want to override the defaults. Default argument values provide an easy way to do this, without having to define lots of functions for the rare exceptions. As Python does not support overloaded methods/functions, default arguments are an easy way of “faking” the overloading behavior.

1.12.3 Cons

Default arguments are evaluated once at module load time. This may cause problems if the argument is a mutable object such as a list or a dictionary. If the function modifies the object (e.g., by appending an item to a list), the default value is modified.

1.12.4 Decision

Okay to use with the following caveat:

Do not use mutable objects as default values in the function or method definition.

Yes: def foo(a, b=None):
         if b is None:
             b = []
Yes: def foo(a, b: Sequence | None = None):
         if b is None:
             b = []
Yes: def foo(a, b: Sequence = ()):  # Empty tuple OK since tuples are immutable.
         ...
from absl import flags
_FOO = flags.DEFINE_string(...)

No:  def foo(a, b=[]):
         ...
No:  def foo(a, b=time.time()):  # Is `b` supposed to represent when this module was loaded?
         ...
No:  def foo(a, b=_FOO.value):  # sys.argv has not yet been parsed...
         ...
No:  def foo(a, b: Mapping = {}):  # Could still get passed to unchecked code.
         ...

1.13 Properties

All class members must be private (prefixed with _). Use properties to expose them publicly when needed.

1.13.1 Definition

Properties provide a way to wrap method calls for getting and setting attributes as standard attribute access. They allow you to control access to private attributes while maintaining a clean public API.

1.13.2 Pros

  • Enforces encapsulation by keeping internal state private.
  • Allows for validation, computation, or side-effects when getting/setting attributes.
  • Can be used to make an attribute read-only.
  • Provides a way to maintain the public interface of a class when the internals evolve independently of class users.
  • Enables lazy evaluation of attributes.

1.13.3 Cons

  • Can hide side-effects much like operator overloading.
  • Can be confusing for subclasses.
  • Adds boilerplate for simple attribute access.

1.13.4 Decision

All instance attributes must start with _ to mark them as private. When you need to expose an attribute publicly, create a property getter and optionally a setter.

Properties should be created with the @property decorator for getters and @<property_name>.setter for setters.

Basic property with getter and setter:

Yes:
  class User:
    def __init__(self, name: str, age: int) -> None:
      self._name = name  # Private attribute
      self._age = age    # Private attribute

    @property
    def name(self) -> str:
      """Get the user's name."""
      return self._name

    @name.setter
    def name(self, value: str) -> None:
      """Set the user's name."""
      if not value:
        raise ValueError("Name cannot be empty")
      self._name = value

    @property
    def age(self) -> int:
      """Get the user's age."""
      return self._age

    @age.setter
    def age(self, value: int) -> None:
      """Set the user's age."""
      if value < 0:
        raise ValueError("Age cannot be negative")
      self._age = value

  # Usage
  user = User("Alice", 30)
  print(user.name)  # Access like an attribute
  user.age = 31     # Set like an attribute

No:
  class User:
    def __init__(self, name: str, age: int) -> None:
      self.name = name  # Public attribute - not allowed!
      self.age = age    # Public attribute - not allowed!

Read-only property (getter only):

Yes:
  class Circle:
    def __init__(self, radius: float) -> None:
      self._radius = radius

    @property
    def radius(self) -> float:
      """Get the circle's radius."""
      return self._radius

    @property
    def area(self) -> float:
      """Calculate the circle's area (read-only)."""
      return 3.14159 * self._radius ** 2

    @property
    def diameter(self) -> float:
      """Calculate the circle's diameter (read-only)."""
      return self._radius * 2

  # Usage
  circle = Circle(5.0)
  print(circle.radius)    # 5.0
  print(circle.area)      # 78.53975
  print(circle.diameter)  # 10.0

Property with validation:

Yes:
  class BankAccount:
    def __init__(self, balance: float) -> None:
      self._balance = balance
      self._transaction_count = 0

    @property
    def balance(self) -> float:
      """Get the current balance."""
      return self._balance

    @balance.setter
    def balance(self, value: float) -> None:
      """Set the balance with validation."""
      if value < 0:
        raise ValueError("Balance cannot be negative")
      self._balance = value
      self._transaction_count += 1

    @property
    def transaction_count(self) -> int:
      """Get the number of transactions (read-only)."""
      return self._transaction_count

  # Usage
  account = BankAccount(1000.0)
  account.balance = 1500.0  # Validation passes
  # account.balance = -100.0  # Raises ValueError

Property with lazy evaluation:

If you need lazy evaluation, use functools.cached_property instead of manual cache management.

Yes:
  from functools import cached_property

  class DataProcessor:
    def __init__(self, data: list[int]) -> None:
      self._data = data

    @property
    def data(self) -> list[int]:
      """Get the data."""
      return self._data

    @cached_property
    def sum(self) -> int:
      """Get the sum of data (lazy evaluation, cached automatically)."""
      return sum(self._data)

    @cached_property
    def average(self) -> float:
      """Calculate average (lazy evaluation, cached automatically)."""
      return sum(self._data) / len(self._data)

  # Usage
  processor = DataProcessor([1, 2, 3, 4, 5])
  print(processor.sum)      # Calculates: 15
  print(processor.sum)      # Returns cached: 15
  print(processor.average)  # Calculates: 3.0

No:
  # Don't manually manage cache
  class DataProcessor:
    def __init__(self, data: list[int]) -> None:
      self._data = data
      self._sum_cache: int | None = None  # Manual cache - avoid this!

    @property
    def sum(self) -> int:
      """Get the sum of data."""
      if self._sum_cache is None:
        self._sum_cache = sum(self._data)
      return self._sum_cache

Note: cached_property computes the value once and caches it for the lifetime of the instance. If you need cache invalidation when data changes, use regular properties or explicit methods instead.

Important notes:

  • Property implementations must be cheap, straightforward, and unsurprising.
  • Don’t use properties for expensive computations; use explicit methods instead.
  • Inheritance with properties can be non-obvious. Be careful when overriding properties in subclasses.
  • Manually implementing a property descriptor is considered a power feature and should be avoided.

1.14 True/False Evaluations

Use the “implicit” false if at all possible (with a few caveats).

1.14.1 Definition

Python evaluates certain values as False when in a boolean context. A quick “rule of thumb” is that all “empty” values are considered false, so 0, None, [], {}, '' all evaluate as false in a boolean context.

1.14.2 Pros

Conditions using Python booleans are easier to read and less error-prone. In most cases, they’re also faster.

1.14.3 Cons

May look strange to C/C++ developers.

1.14.4 Decision

Use the “implicit” false if possible, e.g., if foo: rather than if foo != []:. There are a few caveats that you should keep in mind though:

  • Always use if foo is None: (or is not None) to check for a None value. E.g., when testing whether a variable or argument that defaults to None was set to some other value. The other value might be a value that’s false in a boolean context!
  • Never compare a boolean variable to False using ==. Use if not x: instead. If you need to distinguish False from None then chain the expressions, such as if not x and x is not None:.
  • For sequences (strings, lists, tuples), use the fact that empty sequences are false, so if seq: and if not seq: are preferable to if len(seq): and if not len(seq): respectively.
  • When handling integers, implicit false may involve more risk than benefit (i.e., accidentally handling None as 0). You may compare a value which is known to be an integer (and is not the result of len()) against the integer 0.
Yes: if not users:
         print('no users')

     if i % 10 == 0:
         self.handle_multiple_of_ten()

     def f(x=None):
         if x is None:
             x = []
No:  if len(users) == 0:
         print('no users')

     if not i % 10:
         self.handle_multiple_of_ten()

     def f(x=None):
         x = x or []
  • Note that '0' (i.e., 0 as string) evaluates to true.
  • Note that Numpy arrays may raise an exception in an implicit boolean context. Prefer the .size attribute when testing emptiness of a np.array (e.g. if not users.size).

1.16 Lexical Scoping

Okay to use.

1.16.1 Definition

A nested Python function can refer to variables defined in enclosing functions, but cannot assign to them. Variable bindings are resolved using lexical scoping, that is, based on the static program text. Any assignment to a name in a block will cause Python to treat all references to that name as a local variable, even if the use precedes the assignment. If a global declaration occurs, the name is treated as a global variable.

An example of the use of this feature is:

def get_adder(summand1: float) -> Callable[[float], float]:
    """Returns a function that adds numbers to a given number."""
    def adder(summand2: float) -> float:
        return summand1 + summand2

    return adder

1.16.2 Pros

Often results in clearer, more elegant code. Especially comforting to experienced Lisp and Scheme (and Haskell and ML and …) programmers.

1.16.3 Cons

Can lead to confusing bugs, such as this example based on PEP-0227:

i = 4
def foo(x: Iterable[int]):
    def bar():
        print(i, end='')
    # ...
    # A bunch of code here
    # ...
    for i in x:  # Ah, i *is* local to foo, so this is what bar sees
        print(i, end='')
    bar()

So foo([1, 2, 3]) will print 1 2 3 3, not 1 2 3 4.

1.16.4 Decision

Okay to use.

1.17 Function and Method Decorators

Use decorators judiciously when there is a clear advantage. Follow strict conventions for classmethod and staticmethod.

1.17.1 Definition

Decorators for Functions and Methods (a.k.a “the @ notation”). One common decorator is @property, used for converting ordinary methods into dynamically computed attributes. However, the decorator syntax allows for user-defined decorators as well. Specifically, for some function my_decorator, this:

class C:
    @my_decorator
    def method(self):
        # method body ...

is equivalent to:

class C:
    def method(self):
        # method body ...
    method = my_decorator(method)

1.17.2 Pros

Elegantly specifies some transformation on a method; the transformation might eliminate some repetitive code, enforce invariants, etc.

1.17.3 Cons

Decorators can perform arbitrary operations on a function’s arguments or return values, resulting in surprising implicit behavior. Additionally, decorators execute at object definition time. For module-level objects (classes, module functions, …) this happens at import time. Failures in decorator code are pretty much impossible to recover from.

1.17.4 Decision

Use decorators judiciously when there is a clear advantage. Decorators should follow the same import and naming guidelines as functions. A decorator docstring should clearly state that the function is a decorator. Write unit tests for decorators.

Avoid external dependencies in the decorator itself (e.g. don’t rely on files, sockets, database connections, etc.), since they might not be available when the decorator runs (at import time, perhaps from pydoc or other tools). A decorator that is called with valid parameters should (as much as possible) be guaranteed to succeed in all cases.

Decorators are a special case of “top-level code” - see main for more discussion.

classmethod - Use ONLY for factory methods:

Use @classmethod exclusively for factory methods that create instances of the class. Factory methods provide named constructors that make instance creation more explicit and readable.

Yes:
  class User:
    def __init__(self, name: str, email: str, role: str) -> None:
      self._name = name
      self._email = email
      self._role = role

    @classmethod
    def from_dict(cls, data: dict) -> "User":
      """Factory method: Create User from dictionary."""
      return cls(
        name=data["name"],
        email=data["email"],
        role=data.get("role", "user")
      )

    @classmethod
    def create_admin(cls, name: str, email: str) -> "User":
      """Factory method: Create admin user."""
      return cls(name=name, email=email, role="admin")

  # Usage
  user1 = User.from_dict({"name": "Alice", "email": "alice@example.com"})
  user2 = User.create_admin("Bob", "bob@example.com")

No:
  class Utils:
    @classmethod
    def calculate_total(cls, items: list[int]) -> int:
      """Wrong: This is not a factory method!"""
      return sum(items)

Module-level functions are forbidden - Use classes instead:

Never write module-level functions. All functions must be organized under classes. This ensures better organization and makes dependencies explicit.

Yes:
  # user_service.py
  class UserService:
    def __init__(self, repository: UserRepository) -> None:
      self._repository = repository

    def get_user(self, user_id: str) -> User:
      """Get user by ID."""
      return self._repository.find_by_id(user_id)

    def validate_email(self, email: str) -> bool:
      """Validate email format."""
      return "@" in email and "." in email.split("@")[1]

No:
  # user_service.py
  def get_user(user_id: str) -> User:
    """Wrong: Module-level function!"""
    repository = UserRepository()
    return repository.find_by_id(user_id)

  def validate_email(email: str) -> bool:
    """Wrong: Module-level function!"""
    return "@" in email and "." in email.split("@")[1]

staticmethod - Use for utility classes that don’t need instance state:

Use @staticmethod when you have a class with methods that don’t need access to instance members. However, if you use staticmethod, the entire class must be static. Never mix static and non-static methods in the same class.

Yes:
  # All methods are static - this is a utility class
  class StringUtils:
    @staticmethod
    def to_snake_case(text: str) -> str:
      """Convert text to snake_case."""
      import re
      return re.sub(r'(?<!^)(?=[A-Z])', '_', text).lower()

    @staticmethod
    def to_camel_case(text: str) -> str:
      """Convert text to camelCase."""
      components = text.split('_')
      return components[0] + ''.join(x.title() for x in components[1:])

    @staticmethod
    def truncate(text: str, max_length: int) -> str:
      """Truncate text to max length."""
      return text[:max_length] + "..." if len(text) > max_length else text

  # Usage (no instantiation needed)
  snake = StringUtils.to_snake_case("HelloWorld")
  camel = StringUtils.to_camel_case("hello_world")

No:
  # Wrong: Mixing static and non-static methods
  class UserService:
    def __init__(self, repository: UserRepository) -> None:
      self._repository = repository

    def get_user(self, user_id: str) -> User:
      """Instance method using self._repository."""
      return self._repository.find_by_id(user_id)

    @staticmethod
    def validate_email(email: str) -> bool:
      """Wrong: Don't mix staticmethod with instance methods!"""
      return "@" in email

Yes:
  # Correct: Keep validate_email as instance method
  class UserService:
    def __init__(self, repository: UserRepository) -> None:
      self._repository = repository

    def get_user(self, user_id: str) -> User:
      """Instance method using self._repository."""
      return self._repository.find_by_id(user_id)

    def validate_email(self, email: str) -> bool:
      """Instance method - even though it doesn't use self."""
      return "@" in email

Key rules summary:

  1. @classmethod: Only for factory methods that return instances of the class
  2. No module-level functions: All functions must be under a class
  3. @staticmethod: Only for utility classes where ALL methods are static
  4. Never mix: Don’t combine @staticmethod with instance methods in the same class - even if a method could be static, keep it as an instance method for consistency

1.18 Threading

Do not rely on the atomicity of built-in types.

While Python’s built-in data types such as dictionaries appear to have atomic operations, there are corner cases where they aren’t atomic (e.g. if __hash__ or __eq__ are implemented as Python methods) and their atomicity should not be relied upon. Neither should you rely on atomic variable assignment (since this in turn depends on dictionaries).

Use the queue module’s Queue data type as the preferred way to communicate data between threads. Otherwise, use the threading module and its locking primitives. Prefer condition variables and threading.Condition instead of using lower-level locks.

1.19 Power Features

Avoid these features.

1.19.1 Definition

Python is an extremely flexible language and gives you many fancy features such as custom metaclasses, access to bytecode, on-the-fly compilation, dynamic inheritance, object reparenting, import hacks, reflection (e.g. some uses of getattr()), modification of system internals, __del__ methods implementing customized cleanup, etc.

1.19.2 Pros

These are powerful language features. They can make your code more compact.

1.19.3 Cons

It’s very tempting to use these “cool” features when they’re not absolutely necessary. It’s harder to read, understand, and debug code that’s using unusual features underneath. It doesn’t seem that way at first (to the original author), but when revisiting the code, it tends to be more difficult than code that is longer but is straightforward.

1.19.4 Decision

Avoid these features in your code.

Standard library modules and classes that internally use these features are okay to use (for example, abc.ABCMeta, dataclasses, and enum).

1.20 Modern Python: from future imports

New language version semantic changes may be gated behind a special future import to enable them on a per-file basis within earlier runtimes.

1.20.1 Definition

Being able to turn on some of the more modern features via from __future__ import statements allows early use of features from expected future Python versions.

1.20.2 Pros

This has proven to make runtime version upgrades smoother as changes can be made on a per-file basis while declaring compatibility and preventing regressions within those files. Modern code is more maintainable as it is less likely to accumulate technical debt that will be problematic during future runtime upgrades.

1.20.3 Cons

Such code may not work on very old interpreter versions prior to the introduction of the needed future statement. The need for this is more common in projects supporting an extremely wide variety of environments.

1.20.4 Decision

from future imports

Use of from __future__ import statements is encouraged. It allows a given source file to start using more modern Python syntax features today. Once you no longer need to run on a version where the features are hidden behind a __future__ import, feel free to remove those lines.

In code that may execute on versions as old as 3.5 rather than >= 3.7, import:

from __future__ import generator_stop

For more information read the Python future statement definitions documentation.

Please don’t remove these imports until you are confident the code is only ever used in a sufficiently modern environment. Even if you do not currently use the feature a specific future import enables in your code today, keeping it in place in the file prevents later modifications of the code from inadvertently depending on the older behavior.

Use other from __future__ import statements as you see fit.

1.21 Type Annotated Code

All code must have type annotations. Type-check the code with ty and Pyright before committing.

1.21.1 Definition

Type annotations (or “type hints”) are for function or method arguments and return values:

def func(a: int) -> list[int]:
    return [a, a * 2]

You can also declare the type of a variable using type annotations:

a: SomeType = some_func()

For third-party or extension modules without type hints, annotations can be in stub .pyi files.

1.21.2 Pros

  • Type annotations improve the readability and maintainability of your code.
  • Type checkers convert many runtime errors to build-time errors.
  • Provides better IDE support with autocomplete and refactoring.
  • Serves as inline documentation for function signatures.
  • Reduces bugs by catching type mismatches early.

1.21.3 Cons

  • You must keep type declarations up to date as code evolves.
  • Type annotations add some verbosity to code.
  • Complex types (especially generics) can be hard to write correctly.

1.21.4 Decision

All code must be fully type annotated. Every function, method, and variable that isn’t obvious from context must have type hints.

We use a two-layer type checking approach:

  1. ty: Gradual type checker focusing on return types and argument types
  2. Pyright: Static type checker for structural type validation

Both tools must pass without errors before code can be committed. See Section 1.1 Linting and Type Checking for details on running these tools.

Annotate all functions and methods:

Yes:
  class UserService:
    def __init__(self, repository: UserRepository) -> None:
      self._repository = repository

    def get_user(self, user_id: str) -> User:
      """Get user by ID."""
      user = self._repository.find_by_id(user_id)
      if user is None:
        raise UserNotFoundError(f"User {user_id} not found")
      return user

    def list_users(self, limit: int = 100) -> list[User]:
      """List users with optional limit."""
      return self._repository.find_all(limit=limit)

No:
  class UserService:
    def __init__(self, repository):  # Missing type hints!
      self._repository = repository

    def get_user(self, user_id):  # Missing type hints!
      user = self._repository.find_by_id(user_id)
      if user is None:
        raise UserNotFoundError(f"User {user_id} not found")
      return user

Annotate variables when types aren’t obvious:

Yes:
  # Type is obvious from assignment
  count = 0
  name = "Alice"
  is_active = True

  # Type isn't obvious - annotate it
  users: list[User] = []
  config: dict[str, Any] = load_config()
  cache: dict[str, User | None] = {}

No:
  # Don't annotate when obvious
  count: int = 0  # Unnecessary
  name: str = "Alice"  # Unnecessary

  # Missing annotation when not obvious
  users = []  # What type of list?
  config = load_config()  # What does this return?

Use Any sparingly:

Only use Any when you truly need to accept any type. Prefer specific types or unions.

Yes:
  def serialize_user(user: User) -> dict[str, str | int | bool]:
    """Specific union type."""
    return {"name": user.name, "age": user.age, "active": user.is_active}

Maybe:
  def serialize(obj: Any) -> dict[str, Any]:
    """Only use Any when truly generic."""
    return {"type": type(obj).__name__, "value": str(obj)}

No:
  def serialize_user(user: User) -> dict[str, Any]:
    """Too vague - be more specific!"""
    return {"name": user.name, "age": user.age, "active": user.is_active}

Generic types:

Use generics for reusable container types:

from typing import TypeVar, Generic

T = TypeVar("T")

class Repository(Generic[T]):
  def __init__(self, model_class: type[T]) -> None:
    self._model_class = model_class

  def find_by_id(self, id: str) -> T | None:
    """Find entity by ID."""
    # Implementation here
    pass

  def find_all(self) -> list[T]:
    """Find all entities."""
    # Implementation here
    pass

# Usage
user_repo: Repository[User] = Repository(User)
user: User | None = user_repo.find_by_id("123")

1.22 Testing

Write tests using pytest. Tests must be simple functions without classes.

1.22.1 Definition

We use pytest as our testing framework. Tests are written as simple functions prefixed with test_. We only use unittest for mocking utilities (unittest.mock), never for test structure.

1.22.2 Pros

  • Simple, flat test structure that’s easy to read and understand
  • pytest provides excellent assertion introspection without boilerplate
  • Fixtures enable clean test setup and teardown
  • No unnecessary class hierarchy or inheritance

1.22.3 Cons

  • Requires discipline to avoid creating test classes when not needed
  • May be unfamiliar to developers coming from unittest background

1.22.4 Decision

Write tests as functions, not classes:

All tests must be written as standalone functions. Do not use test classes except when absolutely necessary (see exemptions below).

Yes:
  def test_user_service_creates_user():
    """Test that UserService can create a new user."""
    service = UserService(repository=MockRepository())
    user = service.create_user("Alice", "alice@example.com")
    assert user.name == "Alice"
    assert user.email == "alice@example.com"

  def test_user_service_validates_email():
    """Test that UserService validates email format."""
    service = UserService(repository=MockRepository())
    with pytest.raises(ValueError, match="Invalid email"):
      service.create_user("Bob", "invalid-email")

No:
  class TestUserService:  # Don't use classes!
    def test_creates_user(self):
      service = UserService(repository=MockRepository())
      user = service.create_user("Alice", "alice@example.com")
      assert user.name == "Alice"

Use unittest.mock for mocking:

While we use pytest for test structure, use unittest.mock for mocking and patching.

Yes:
  from unittest.mock import Mock, patch, MagicMock

  def test_user_service_calls_repository():
    """Test that UserService calls the repository correctly."""
    mock_repository = Mock()
    mock_repository.save.return_value = User(id="123", name="Alice")

    service = UserService(repository=mock_repository)
    user = service.create_user("Alice", "alice@example.com")

    mock_repository.save.assert_called_once()
    assert user.name == "Alice"

  @patch('ai.services.external_api.requests.post')
  def test_external_api_call(mock_post):
    """Test external API call with patch."""
    mock_post.return_value.json.return_value = {"status": "success"}

    result = call_external_api()

    assert result["status"] == "success"
    mock_post.assert_called_once()

Use pytest fixtures for setup:

Use pytest fixtures to share setup code across tests.

Yes:
  import pytest

  @pytest.fixture
  def user_repository():
    """Create a test user repository."""
    return MockUserRepository()

  @pytest.fixture
  def user_service(user_repository):
    """Create a test user service."""
    return UserService(repository=user_repository)

  def test_create_user(user_service):
    """Test user creation."""
    user = user_service.create_user("Alice", "alice@example.com")
    assert user.name == "Alice"

  def test_validate_email(user_service):
    """Test email validation."""
    with pytest.raises(ValueError):
      user_service.create_user("Bob", "invalid")

Use descriptive test names:

Test function names should clearly describe what is being tested.

Yes:
  def test_user_service_creates_user_with_valid_data():
    """Clear description of what's tested."""
    pass

  def test_user_service_raises_error_for_duplicate_email():
    """Clear description of error case."""
    pass

No:
  def test_user_service():  # Too vague
    pass

  def test_1():  # No description
    pass

Organize tests by file structure:

Mirror the source code structure in your tests directory.

services/py/ai/
├── ai/
│   ├── services/
│   │   └── user_service.py
│   └── repositories/
│       └── user_repository.py
└── tests/
    ├── services/
    │   └── test_user_service.py
    └── repositories/
        └── test_user_repository.py

1.22.5 Exemptions

Test classes are ONLY allowed in these specific cases:

  1. When using pytest parametrization that benefits from class grouping (rare)
  2. When testing a specific class with many related test cases that share complex fixtures (use sparingly)

Even in these cases, prefer flat functions if possible.

2 Parting Words

BE CONSISTENT.

If you’re editing code, take a few minutes to look at the code around you and determine its style. If they use _idx suffixes in index variable names, you should too. If their comments have little boxes of hash marks around them, make your comments have little boxes of hash marks around them too.

The point of having style guidelines is to have a common vocabulary of coding so people can concentrate on what you’re saying rather than on how you’re saying it. We present global style rules here so people know the vocabulary, but local style is also important. If code you add to a file looks drastically different from the existing code around it, it throws readers out of their rhythm when they go to read it.

However, there are limits to consistency. It applies more heavily locally and on choices unspecified by the global style. Consistency should not generally be used as a justification to do things in an old style without considering the benefits of the new style, or the tendency of the codebase to converge on newer styles over time.