{"record":{"id":"ec4ed414c397e36a","repo":"apache/beam","slug":"s-type-constraint-violated-valid-object-instance-must-be-of","errorCode":null,"errorMessage":"%s type-constraint violated. Valid object instance must be of type '%s'. Instead, an instance of '%s' was received.","messagePattern":"(.+?) type-constraint violated\\. Valid object instance must be of type '(.+?)'\\. Instead, an instance of '(.+?)' was received\\.","errorType":"validation","errorClass":"CompositeTypeHintError","httpStatus":null,"severity":"error","filePath":"sdks/python/apache_beam/typehints/typehints.py","lineNumber":279,"sourceCode":"\n  def __hash__(self):\n    return hash(self.inner_type) ^ 13 * hash(type(self))\n\n  def _inner_types(self):\n    yield self.inner_type\n\n  def _constraint_for_index(self, idx):\n    \"\"\"Returns the type at the given index.\"\"\"\n    return self.inner_type\n\n  def _consistent_with_check_(self, sub):\n    return (\n        isinstance(sub, self.__class__) and\n        is_consistent_with(sub.inner_type, self.inner_type))\n\n  def type_check(self, sequence_instance):\n    if not isinstance(sequence_instance, self._sequence_type):\n      raise CompositeTypeHintError(\n          \"%s type-constraint violated. Valid object instance \"\n          \"must be of type '%s'. Instead, an instance of '%s' \"\n          \"was received.\" % (\n              self._sequence_type.__name__.title(),\n              self._sequence_type.__name__.lower(),\n              sequence_instance.__class__.__name__))\n\n    for index, elem in enumerate(sequence_instance):\n      try:\n        check_constraint(self.inner_type, elem)\n      except SimpleTypeHintError:\n        raise CompositeTypeHintError(\n            '%s hint type-constraint violated. The type of element #%s in '\n            'the passed %s is incorrect. Expected an instance of type %s, '\n            'instead received an instance of type %s.' % (\n                repr(self),\n                index,\n                repr(self._sequence_type),","sourceCodeStart":261,"sourceCodeEnd":297,"githubUrl":"https://github.com/apache/beam/blob/12126d8942aaf848030c478b4c6a28c6af861c66/sdks/python/apache_beam/typehints/typehints.py#L261-L297","documentation":"Apache Beam's typehints module raises CompositeTypeHintError from SequenceTypeConstraint.type_check when a value annotated as a sequence type-hint (e.g. List[int]) is not an instance of the expected Python sequence container class. The library validates PTransform inputs/outputs against declared type hints and fails fast when the concrete object's class differs from the constraint's sequence type (list, tuple, set, etc.).","triggerScenarios":"Passing an object whose class is not the constrained sequence type to a type_check call, e.g. annotating a transform with List[int] but producing a tuple, or vice versa; also triggered when check_constraint dispatches a SequenceTypeConstraint against a non-sequence instance.","commonSituations":"Mismatch between declared and actual container types (list vs tuple vs set) when wiring Beam pipelines; refactors that change a transform's output container without updating with_output_types; deserialized objects (e.g. from JSON) that arrive as lists where tuples were hinted.","solutions":["Make the passed value an instance of the required sequence type (e.g. wrap it in list(...) or tuple(...) as the hint requires).","Update the type hint (with_input_types/with_output_types or annotation) to match the actual container class produced.","Use typing.Any or a broader constraint temporarily to isolate which pipeline stage produces the wrong container.","Log sequence_instance.__class__ at the failing stage to confirm which element path is being type-checked."],"exampleFix":"# before\np | 'parse' >> beam.Map(lambda s: (s[0], int(s[1]))).with_output_types(List[Tuple[str, int]])\n# after\np | 'parse' >> beam.Map(lambda s: [s[0], int(s[1])]).with_output_types(List[Tuple[str, int]])","handlingStrategy":"type-guard","validationCode":"def assert_sequence(value, seq_type):\n    if not isinstance(value, seq_type):\n        raise TypeError(f'expected {seq_type.__name__}, got {type(value).__name__}')\n    return value","typeGuard":"def is_list_of(value, elem_type):\n    return isinstance(value, list) and all(isinstance(x, elem_type) for x in value)","tryCatchPattern":"try:\n    run_typed_stage(pcoll)\nexcept CompositeTypeHintError as e:\n    logger.error('container type mismatch: %s', e)\n    raise","preventionTips":["Keep hint containers and produced containers identical (list vs tuple vs set)","Add type checks in unit tests using beam.typehints.check_constraint on sample outputs","Run pipelines with --type_check_strict or default runtime type checking in CI"],"tags":["python","apache-beam","typehints","type-error"],"backgroundTag":"type-mismatch","analyzedSha":"12126d8942aaf848030c478b4c6a28c6af861c66","analyzedAt":"2026-09-13T01:50:10.254Z","contentChangedAt":"2026-09-13T01:50:10.254Z","schemaVersion":2},"datasetVersion":"2026-09-14T21:17:11.552Z"}