You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过循环在isinstance函数中传递元组?代码问题求助

Fixing Type Validation with Looped Tuple Checks in isinstance

Let's walk through fixing your code step by step. There are a few key issues preventing your type validation from working correctly:

Key Issues in Your Code

  1. Incorrect isinstance Call: You're passing a single tuple (i) to isinstance, but it requires two arguments: the value to check and the expected type(s). You need to unpack each tuple in key_data into these two separate values.
  2. KeyError Handling: Your except clause overwrites the err_path variable and doesn't clearly indicate which key is missing.
  3. Potential Unhandled Missing Keys: Accessing payload["Device"] directly can raise a KeyError if "Device" isn't present in the payload.

Corrected Code

Here's the revised version with explanations:

def validate_record_schema():
    """Validate that the 0 or more Payload dicts in record use proper types"""
    try:
        for record in test1:  # Assuming `test1` is your list of target records
            for device_entry in record.get('Payload', []):
                payload = device_entry.get('Payload', None)
                if payload is None:
                    continue
                # Check if "Device" exists in payload before accessing it
                if "Device" not in payload:
                    print("Missing key: 'Device' in payload")
                    return False
                device = payload["Device"]
                
                # Define your value-type pairs for validation
                key_data = (
                    (device["ManualAdded"], bool),
                    (device["Location"], str)
                )
                
                for value, expected_type in key_data:
                    # Unpack each tuple and validate the type
                    if not isinstance(value, expected_type):
                        print(f"Invalid type for '{value}': expected {expected_type.__name__}")
                        return False
    except KeyError as e:
        print(f"Missing required key: {e}")
        return False
    return True

# Call the function and print the validation result
print(validate_record_schema())

What Changed?

  • Unpacking Tuples in the Loop: Instead of passing the entire tuple to isinstance, we unpack each entry into value and expected_type, then use these as the two required arguments for the type check.
  • Explicit "Device" Check: Added a check to ensure "Device" exists in the payload before accessing it, with a clear error message to aid debugging.
  • Improved KeyError Handling: Now captures the exact missing key from the exception and prints it, making it easier to identify where the schema breaks.
  • Clear Error Messages: Added specific messages for type mismatches and missing keys, so you know exactly what's wrong without extra guesswork.

This code will now correctly loop through your type-check tuples and validate each value against its expected type.

内容的提问来源于stack exchange,提问作者nrs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:36:16