We use specific imports rather than wildcards, always include from __future__ import annotations when needed, and organize imports in four distinct groups with alphabetical ordering within each group. Related imports are grouped together, and we prefer absolute imports for clarity.
Import Style
Use from __future__ import annotations at the top of files that use forward references
We use snake_case for variables and functions, PascalCase for classes, UPPER_SNAKE_CASE for constants, and single leading underscores for private members. Names should be descriptive and avoid abbreviations unless they’re well-known in the domain.
Variables and Functions
Use snake_case for variables, functions, and module names
Use descriptive names that clearly indicate purpose
We requrie comprehensive type annotations on functions and classes. We use keyword-only arguments for optional parameters, and
group logically.
Function Signatures
Always include type annotations for parameters and return values
Use keyword-only arguments for optional parameters when appropriate
Group related parameters together
Copy
# Good: Fully annotate parameter and return typesdef process_data(items: list[str]) -> list[str]: return items# Good: Use keyword-only arguments for optional parameters when appropriatedef compile( source: SourceCode, *, src_dir: Path=Path("src"), build_dir: Path=Path("build"), config: BuildConfig="MinSizeRel",) -> CompiledCode | None:
Class Definitions
Inherit from appropriate base classes (ABC, BaseModel, etc.)
Use abstract methods when defining interfaces
Include type annotations for class attributes
Copy
# Good: Inherit from an appropriate base classclass Database(ABC): # Good: Use abstract methods when defining interfaces @abstractmethod def search( self, query: str, *, limit: int = 10 ) -> list[Item]: """ Search for items given a query """ pass
# CHECK # This might have issues with complex nested structuresif isinstance(value, dict): process_dict(value)# INCOMPLETE # Add support for additional tensor typestensor_type = get_basic_tensor_type(input_tensor)
We write highly ergonomic code that is easy to both look at and reason about:
Line Length
Maximum line length: 120 characters
Break long lines using parentheses for natural grouping
Copy
# Good: Long list declarations over multiple linesshell_args = [ f"echo", f"'Hello world'",]# Good: Long function calls over multiple linesresult = some_long_function_name( first_argument, second_argument, third_argument)
Spacing
Use 4 spaces for indentation
No trailing whitespace
Single blank line between function and class definitions
Use comments to separate logical blocks within functions or methods instead of empty lines:
Copy
def process_model(model_path: Path) -> ProcessedModel: # Load and validate model model = load_model(model_path) validate_model_format(model) # Process model layers layers = extract_layers(model) optimized_layers = optimize_layers(layers) # Generate output processed_model = create_processed_model(optimized_layers) return processed_model
String Formatting
Use f-strings for string interpolation
Use double quotes for strings consistently
Use triple double quotes for multiline strings
Copy
# Use double quotes for string literalsgreeting = "Hello and have a nice day!"# Use F-strings for string interpolationsql_query = f"SELECT * FROM {table_name} WHERE id = {item_id}"# Use triple double quotes for multiline stringstemplate = """This is a multilinestring template with {variable}."""
We encourage defining a small set of custom exception types that can be explicitly handled:
Exception Classes
Create specific exception classes for different error types:
Copy
class CompileError (Exception): """ Compile error. """
Error Messages
Provide clear, actionable error messages
Include context about what failed and why
Copy
if param_type is None: raise CompileError( f"Missing type annotation for parameter `{name}` in " f"function [hot_pink]{func.__name__}[/hot_pink]." )
Exception Handling
Catch specific errors when it makes sense to do so.
When propagating errors from an exception handler, chain exceptions with raise ... from ex to preserve context.
Copy
try: result = risky_operation()except SpecificError as ex: logger.error(f"Operation failed: {ex}") raise CompileError(f"Failed to process: {ex}") from exexcept Exception as ex: logger.exception("Unexpected error") raise
We prefer well-maintained packages with pinned versions for critical dependencies, use optional import patterns with try/except blocks for non-critical features, and favor relative imports for internal modules.
External Dependencies
Prefer well-maintained, widely-used packages
Pin versions for critical dependencies
Use optional imports for non-critical features
Copy
# Optional import patterntry: from onnxruntime import InferenceSessionexcept ImportError: InferenceSession = Nonedef onnx_model_inference(model): if InferenceSession and isinstance(model, InferenceSession): # Handle ONNX model pass
Internal Dependencies
Use relative imports for internal modules
Keep dependencies between modules minimal
Avoid circular imports
Assistant
Responses are generated using AI and may contain mistakes.