Google Style API Documentation¶
Documentation Style
This page demonstrates API documentation using Google-style docstrings, which provide a clean and readable format popular in many open-source projects.
Overview¶
Google-style docstrings use a simple, indented format that's easy to read and write. They're particularly well-suited for:
- Open-source projects
- Team collaborations
- General-purpose libraries
- Web APIs and services
DataProcessor Class¶
src.docstring_examples.google_style.DataProcessor
¶
Comprehensive data processor with loading, transformation, and export.
This class provides a complete data processing pipeline including data loading, transformation operations, validation, and export functionality. It supports various data formats and provides extensive configuration options.
The processor maintains internal state and provides detailed logging of all operations for debugging and monitoring purposes.
Attributes:
Name | Type | Description |
---|---|---|
data |
Optional[Dict[str, Any]]
|
Currently loaded data (None if no data loaded) |
transformations_applied |
Number of transformations applied to current data |
|
export_count |
Number of times data has been exported |
|
validation_enabled |
Whether to validate data during operations |
Example
Complete workflow example:
# Create processor with validation enabled
processor = DataProcessor("sales_data", validation_enabled=True)
# Load data from various sources
processor.load_data({"product": "Widget", "sales": 1000})
processor.load_from_file("additional_data.json")
# Apply transformations
processor.transform_data(
lambda x: x * 1.1 if isinstance(x, (int, float)) else x
)
processor.apply_filter(lambda item: item.get("sales", 0) > 500)
# Export results
processor.export_data("processed_results.json")
Note
This processor is thread-safe for read operations but not for concurrent modifications. Use appropriate locking mechanisms if sharing across threads.
Initialize the data processor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Descriptive name for this processor instance |
required |
validation_enabled
|
bool
|
Whether to enable data validation (default: True) |
True
|
max_transformations
|
int
|
Maximum number of transformations allowed (default: 100) |
100
|
Raises:
Type | Description |
---|---|
ValueError
|
If name is empty or max_transformations is negative |
Example
Source code in src/docstring_examples/google_style.py
Attributes¶
status
property
¶
Get the current processor status.
Returns:
Type | Description |
---|---|
str
|
String indicating current status ("active" or "inactive") |
Functions¶
load_data
¶
Load data into the processor.
This method accepts data in dictionary or list format and stores it internally for subsequent processing operations. The data is validated if validation is enabled.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
Union[Dict[str, Any], List[Dict[str, Any]]]
|
Data to load - either a single dictionary or list of dictionaries |
required |
Raises:
Type | Description |
---|---|
ProcessingError
|
If data validation fails or processor is inactive |
TypeError
|
If data is not in expected format |
Example
Source code in src/docstring_examples/google_style.py
load_from_file
¶
Load data from a JSON file.
Reads data from the specified file path and loads it into the processor. Supports both string paths and Path objects.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
file_path
|
Union[str, Path]
|
Path to the JSON file to load |
required |
Raises:
Type | Description |
---|---|
ProcessingError
|
If file cannot be read or contains invalid JSON |
FileNotFoundError
|
If the specified file does not exist |
PermissionError
|
If insufficient permissions to read the file |
Example
Source code in src/docstring_examples/google_style.py
transform_data
¶
Apply a transformation function to all data values.
Applies the provided transformation function to each value in the loaded data. The transformation preserves the data structure while modifying individual values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
transformation_func
|
Callable[[Any], Any]
|
Function to apply to each data value. Should accept any value and return the transformed value. |
required |
Returns:
Type | Description |
---|---|
ProcessingResult
|
Dictionary containing transformation results with keys: - 'records_processed': Number of records processed - 'transformations_applied': Total transformations applied to this dataset - 'success': Whether the transformation completed successfully |
Raises:
Type | Description |
---|---|
ProcessingError
|
If no data is loaded, processor is inactive, or max transformations exceeded |
ValueError
|
If transformation_func is not callable |
Example
# Convert all strings to uppercase
result = processor.transform_data(
lambda x: x.upper() if isinstance(x, str) else x
)
# Apply mathematical transformation to numbers
result = processor.transform_data(
lambda x: x * 1.1 if isinstance(x, (int, float)) else x
)
# Complex transformation with type checking
def complex_transform(value):
if isinstance(value, str):
return value.strip().title()
elif isinstance(value, (int, float)):
return round(value * 1.05, 2)
return value
result = processor.transform_data(complex_transform)
Source code in src/docstring_examples/google_style.py
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 |
|
apply_filter
¶
Filter data records based on a predicate function.
Removes records that don't match the filter criteria. The filter function should return True for records to keep and False for records to remove.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_func
|
Callable[[Dict[str, Any]], bool]
|
Predicate function that accepts a record dictionary and returns True to keep the record, False to remove it |
required |
Returns:
Type | Description |
---|---|
ProcessingResult
|
Dictionary containing filter results with keys: - 'records_before': Number of records before filtering - 'records_after': Number of records after filtering - 'records_removed': Number of records removed - 'success': Whether the filter operation completed successfully |
Raises:
Type | Description |
---|---|
ProcessingError
|
If no data is loaded or processor is inactive |
ValueError
|
If filter_func is not callable |
Example
# Keep only records with score > 80
result = processor.apply_filter(lambda record: record.get('score', 0) > 80)
# Keep records with specific status
result = processor.apply_filter(
lambda record: record.get('status') == 'active'
)
# Complex filter with multiple conditions
def complex_filter(record):
return (record.get('score', 0) > 70 and
record.get('active', False) and
len(record.get('name', '')) > 0)
result = processor.apply_filter(complex_filter)
Source code in src/docstring_examples/google_style.py
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 |
|
export_data
¶
Export processed data to a file.
Saves the current processed data to the specified file path in the requested format. Currently supports JSON format with plans for additional formats in future versions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
file_path
|
Union[str, Path]
|
Output file path for the exported data |
required |
format
|
str
|
Export format ("json" currently supported, default: "json") |
'json'
|
Raises:
Type | Description |
---|---|
ProcessingError
|
If no data to export, processor inactive, or export fails |
ValueError
|
If format is not supported |
PermissionError
|
If insufficient permissions to write to the file |
Example
Source code in src/docstring_examples/google_style.py
get_statistics
¶
Get comprehensive statistics about the processor and its data.
Returns detailed information about the current state of the processor, including data counts, transformation history, and processing metrics.
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Dictionary containing statistics with keys: - 'processor_name': Name of this processor instance - 'processor_status': Current status (active/inactive) - 'data_loaded': Whether data is currently loaded - 'record_count': Number of records currently loaded - 'transformations_applied': Number of transformations applied - 'export_count': Number of times data has been exported - 'validation_enabled': Whether validation is enabled - 'created_at': When the processor was created - 'uptime_seconds': How long the processor has existed |
Example
Source code in src/docstring_examples/google_style.py
process
¶
Process data using the internal pipeline.
Implementation of the abstract process method from BaseProcessor. This method provides a simplified interface for basic data processing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
Any
|
Data to process |
required |
Returns:
Type | Description |
---|---|
Any
|
Processed data |
Raises:
Type | Description |
---|---|
ProcessingError
|
If processing fails |
Source code in src/docstring_examples/google_style.py
deactivate
¶
Deactivate the processor.
Once deactivated, the processor should not perform any operations until reactivated.
Source code in src/docstring_examples/google_style.py
ProcessingError Exception¶
src.docstring_examples.google_style.ProcessingError
¶
ProcessingError(message: str, error_code: Optional[str] = None, original_error: Optional[Exception] = None)
Bases: Exception
Custom exception for data processing errors.
This exception is raised when data processing operations fail due to invalid data, configuration errors, or runtime issues.
Attributes:
Name | Type | Description |
---|---|---|
message |
Error message describing the failure |
|
error_code |
Optional error code for categorization |
|
original_error |
Original exception that caused this error |
Initialize ProcessingError.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
Descriptive error message |
required |
error_code
|
Optional[str]
|
Optional categorization code |
None
|
original_error
|
Optional[Exception]
|
The original exception if this is a wrapper |
None
|
Module-Level Functions¶
Functions Coming Soon
Module-level function documentation will be added when the source code is available.
Example Usage¶
from docstring_examples.google_style import DataProcessor
# Create a processor instance
processor = DataProcessor(
name="sales_analytics",
validation_enabled=True,
max_transformations=10
)
# Load and process data
processor.load_data(sales_data)
processor.transform_data(lambda x: x.upper() if isinstance(x, str) else x)
processor.apply_filter(lambda record: record.get('sales', 0) > 1000)
# Export results
processor.export_data('output.json')
Style Benefits¶
Readability¶
- Clean, minimal syntax
- Natural indentation
- Easy to scan
Tooling Support¶
- Excellent IDE support
- Works with most documentation generators
- Compatible with type hints
Best Practices¶
- Keep descriptions concise
- Use consistent formatting
- Include type information
- Provide clear examples