

# Lambda コンテキストオブジェクトを使用して Python 関数の情報を取得する
<a name="python-context"></a>

Lambda で関数が実行されると、コンテキストオブジェクトが[ハンドラー](python-handler.md)に渡されます。このオブジェクトは、呼び出し、関数、および実行関数に関する情報を示すメソッドおよびプロパティを提供します。コンテキストオブジェクトが関数ハンドラーに渡される方法の詳細については、「[Python の Lambda 関数ハンドラーの定義](python-handler.md)」をご参照ください。

**context メソッド**
+ `get_remaining_time_in_millis` — 実行がタイムアウトするまでの残り時間をミリ秒で返します。

**context プロパティ**
+ `function_name` － Lambda 関数の名前。
+ `function_version` － 関数の[バージョン](configuration-versions.md)。
+ `invoked_function_arn` － 関数を呼び出すために使用される Amazon リソースネーム (ARN)。呼び出し元でバージョン番号またはエイリアスが指定されているかどうかを示します。
+ `memory_limit_in_mb` － 関数に割り当てられたメモリの量。
+ `aws_request_id` － 呼び出しリクエストの ID。
+ `log_group_name` － 関数のロググループ。
+ `log_stream_name` — 関数インスタンスのログストリーム。
+ `identity` — (モバイルアプリケーション) リクエストを認可した Amazon Cognito ID に関する情報。
  + `cognito_identity_id` - 認証された Amazon Cognito ID
  + `cognito_identity_pool_id` — 呼び出しを承認した Amazon Cognito ID プール。
+ `client_context` —（モバイルアプリ）クライアントアプリケーションが Lambda に提供したクライアントコンテキスト。
  + `client.installation_id`
  + `client.app_title`
  + `client.app_version_name`
  + `client.app_version_code`
  + `client.app_package_name`
  + `custom` - モバイルクライアントアプリケーションが設定したカスタム値の `dict`。
  + `env` - `dict` SDK が提供した環境情報の AWS。

Powertools for Lambda (Python) は、Lambda コンテキストオブジェクトのインターフェイス定義を提供します。型ヒントのインターフェイス定義を使用して、Lambda コンテキストオブジェクトの構造をさらに検査したりできます。インターフェイス定義については、GitHub の *powertools-lambda-python* リポジトリの [lambda\$1context.py](https://github.com/aws-powertools/powertools-lambda-python/blob/develop/aws_lambda_powertools/utilities/typing/lambda_context.py) を参照してください。

以下の例は、コンテキスト情報を記録するハンドラ関数を示します。

**Example handler.py**  

```
import time

def lambda_handler(event, context):   
    print("Lambda function ARN:", context.invoked_function_arn)
    print("CloudWatch log stream name:", context.log_stream_name)
    print("CloudWatch log group name:",  context.log_group_name)
    print("Lambda Request ID:", context.aws_request_id)
    print("Lambda function memory limits in MB:", context.memory_limit_in_mb)
    # We have added a 1 second delay so you can see the time remaining in get_remaining_time_in_millis.
    time.sleep(1) 
    print("Lambda time remaining in MS:", context.get_remaining_time_in_millis())
```

上記に一覧表示するオプションに加えて、AWS 用 [AWS Lambda での Python コードの作成](python-tracing.md) X-Ray SDK を使用して、重要なコードパスの識別、パフォーマンスのトレースおよび分析のためにデータをキャプチャすることもできます。