ユースケース: コードの生成とリファクタリング

Gemini Enterprise を使用して、新しいコードを生成したり、既存のコードをリファクタリングしたりできます。

サンプル プロンプト

チャット ボックスに次のようなプロンプトを入力します。

Can you generate a Python function to parse a JSON file and extract specific
keys? Also, can you refactor the code in the attached file to improve its
readability and efficiency?

出力例

このプロンプトに対して、Gemini Enterprise は次のような出力を生成します。

もちろんです。両方のリクエストに対応できます。

まず、JSON ファイルを解析して指定されたキーのリストを抽出する汎用 Python 関数を次に示します。これには、ファイルが見つからない、JSON コンテンツが無効であるなどの一般的な問題に対するエラー処理が含まれています。

JSON を解析してキーを抽出する関数

import json

def extract_keys_from_json(file_path, keys_to_extract):
    """
    Parses a JSON file and extracts values for a specific list of keys.

    Args:
        file_path (str): The path to the JSON file.
        keys_to_extract (list): A list of strings representing the keys to extract.

    Returns:
        dict: A dictionary containing the extracted keys and their values.
              Returns an empty dictionary if the file is not found or is invalid.
    """
    extracted_data = {}
    try:
        with open(file_path, 'r') as f:
            data = json.load(f)
            # ...

リファクタリングされたコード

以下に、ご提供いただいた hi.py ファイルのリファクタリング バージョンを示します。主な改善点は、深くネストされた if ステートメントを削除することで、コードの安全性と可読性を高めることに重点を置いています。

このバージョンでは、.get() メソッドを使用します。これは、存在しない可能性のあるディクショナリ キーにアクセスするためのより「Pythonic」な方法です。これにより、KeyError 例外を回避し、コードをフラットにして追跡しやすくすることができます。

import json

def update_user_status_refactored(json_data):
    """
    Parses user data, updates status, and handles nested keys safely.
    """
    data = json.loads(json_data)

    # Safely get the email using .get() to avoid errors if keys are missing
    # .get('user', {}) returns an empty dict if 'user' is not found
    email = data.get('user', {}).get('details', {}).get('email')

    if email:
        print(f"Processing user: {email}")

    # Update the user status
    if 'user' in data:
        # ...