Search code examples
pythonjsonpython-3.xisinstance

How can i pass tuples in isinstance through loop?


My code:

def validate_record_schema():
    """Validate that the 0 or more Payload dicts in record
    use proper types"""
    err_path = "root"
    try:
        for record in test1:
            for device in record.get('Payload', []):
                payload = device.get('Payload', None)
                if payload is None:
                    continue
                device = payload["Device"]
                key_data = ((device["ManualAdded"],bool), (device["Location"],str))

                for i in key_data:
                        if not isinstance(i):
                            return False

    except KeyError as err_path:
        print("missing key")
        return False
    return True

print(validate_record_schema())

I want to do it like below but i am not able to do it.

key_data = ((device["ManualAdded"],bool), (device["Location"],str))

                for i in key_data:
                        if not isinstance(i):
                            return False

If i am doing like below it's working

if not isinstance((device["ManualAdded"],bool)):
   return False

But i need to do it like above.How can i do this?

Json data

test1 = [{'Id': '12', 'Type': 'DevicePropertyChangedEvent', 'Payload': [{'DeviceType': 'producttype', 'DeviceId': 2, 'IsFast': False, 'Payload': {'DeviceInstanceId': 2, 'IsResetNeeded': False, 'ProductType': 'product'
, 'Product': {'Family': 'home'}, 'Device': {'DeviceFirmwareUpdate': {'DeviceUpdateStatus': None, 'DeviceUpdateInProgress': None, 'DeviceUpdateProgress': None, 'LastDeviceUpdateId': None}, 'ManualAdded': False,
 'Name': {'Value': 'Jigital60asew', 'IsUnique': True}, 'State': None, 'Location': "dg", 'Serial': None, 'Version': '2.0.1.100'}}}]}]

Solution

  • You can expand the tuple and pass its members as individual args using the * operator.

    key_data = (('This is a string', str), ('This is a string', bool))
    
    for i in key_data:
        if isinstance(*i):
            print("yes")
        else:
            print("no")