如何通过循环在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
- Incorrect
isinstanceCall: You're passing a single tuple (i) toisinstance, but it requires two arguments: the value to check and the expected type(s). You need to unpack each tuple inkey_datainto these two separate values. - KeyError Handling: Your
exceptclause overwrites theerr_pathvariable and doesn't clearly indicate which key is missing. - 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 intovalueandexpected_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
相关产品推荐
相关产品推荐

