Typing Stubs for AWS X-Ray SDK for Python

2.15.0.20260408 · active · verified Tue Apr 14

This package provides static type annotations (stubs) for the `aws-xray-sdk` Python library. It enables type checkers like MyPy, Pyright, or Pylance to perform static analysis and provide better autocompletion and error detection for code using `aws-xray-sdk`. It is part of the `typeshed` project and receives regular updates, with the current version targeting `aws-xray-sdk==2.15.*`.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the underlying `aws-xray-sdk` library, which `types-aws-xray-sdk` provides type hints for. It includes configuration, patching, and a basic traced function using a context manager. To verify the stubs, you would typically run a type checker like MyPy against this code. The commented-out line shows an example of a type error that `types-aws-xray-sdk` would help detect. Remember that for actual tracing, the AWS X-Ray daemon must be running and accessible.

import os
from aws_xray_sdk.core import xray_recorder, patch_all
from aws_xray_sdk.core.segments import Segment

# Install the X-Ray daemon locally or ensure it's available
# Docs: https://docs.aws.amazon.com/xray/latest/devguide/xray-daemon.html

# Configure X-Ray Recorder (example values)
xray_recorder.configure(
    service='MyApplication',
    sampling=False, # For simplicity in this example
    context_missing='LOG_ERROR',
    daemon_address=os.environ.get('AWS_XRAY_DAEMON_ADDRESS', '127.0.0.1:2000')
)

# Apply patches for supported libraries (e.g., boto3, requests)
patch_all()

def my_traced_function(item_id: str) -> str:
    # Type checking will ensure 'begin_segment' returns a Segment
    with xray_recorder.in_segment('MyFunctionSegment') as segment: # type: Segment
        segment.put_annotation('item_id', item_id)
        print(f"Processing item {item_id} within segment {segment.id}")
        return f"Processed {item_id}"

if __name__ == '__main__':
    # Example usage - this code will run and potentially send traces
    # For type checking, save this as `app.py` and run `mypy app.py`
    result = my_traced_function("12345")
    print(result)

    # Demonstrate a type error (uncomment and run mypy to see it)
    # xray_recorder.configure(service=123) # Expected str, got int

view raw JSON →