code: def typed_dict_validation(
      typ: Type[T], instance: Any
  ) -> TypeGuard[T]:
      # https://stackoverflow.com/questions/66665336/validate-python-typeddict-at-runtime
      if not isinstance(instance, dict):
          _logger.error(
              "Validation failed for %s. Instance is not a dict: %s",
              typ,
              type(instance),
          )
          return False
  
      for property_name, property_type in typ.__annotations__.items():
          if property_name not in instance:
              # Check for missing keys
              _logger.error(
                  "Validation failed for %s. Missing key: %s",
                  typ,
                  property_name,
              )
              return False
  
          value = instance[property_name]
          if property_type in (int, float, bool, str):
              # Check for type equality
              if not isinstance(value, property_type):
                  _logger.error(
                      "Validation failed for %s. Wrong type: %s. Expected %s, got %s",
                      typ,
                      property_name,
                      property_type,
                      type(value),
                  )
                  return False
  
          elif get_origin(property_type) == Literal:
              # Check literal.
              if value not in property_type.__args__:
                  _logger.error(
                      "Validation failed for %s. Expect literal to be one of %s, got %s",
                      typ,
                      property_type.__args__,
                      value,
                  )
                  return False
  
          else:
              # Assuming a nested typed dict.
              result = typed_dict_validation(property_type, value)
              if result is False:
                  return False
  
      return True
  
file_path: nni/nni/contrib/training_service/typehint.py
imports: import logging
  from typing import TypedDict, Any, Type, TypeVar, get_origin
  from typing_extensions import Literal, TypeGuard
label_desc: Use image node_id 1 for calling a global function with example usage: typed_dict_validation(typ, instance) and returns: True, False, False, False, False, False