{"record":{"id":"7f381eefed9897b3","repo":"apache/beam","slug":"s-type-constraint-violated-expected-an-instance-of-one-of-s","errorCode":null,"errorMessage":"%s type-constraint violated. Expected an instance of one of: %s, received %s instead.%s","messagePattern":"(.+?) type-constraint violated\\. Expected an instance of one of: (.+?), received (.+?) instead\\.(.+?)","errorType":"validation","errorClass":"CompositeTypeHintError","httpStatus":null,"severity":"error","filePath":"sdks/python/apache_beam/typehints/typehints.py","lineNumber":555,"sourceCode":"      if isinstance(sub, UnionConstraint):\n        # A union type is compatible if every possible type is compatible.\n        # E.g. Union[A, B, C] > Union[A, B].\n        return all(is_consistent_with(elem, self) for elem in sub.union_types)\n      # Other must be compatible with at least one of this union's subtypes.\n      # E.g. Union[A, B, C] > T if T > A or T > B or T > C.\n      return any(is_consistent_with(sub, elem) for elem in self.union_types)\n\n    def type_check(self, instance):\n      error_msg = ''\n      for t in self.union_types:\n        try:\n          check_constraint(t, instance)\n          return\n        except TypeError as e:\n          error_msg = str(e)\n          continue\n\n      raise CompositeTypeHintError(\n          '%s type-constraint violated. Expected an instance of one of: %s, '\n          'received %s instead.%s' % (\n              repr(self),\n              tuple(repr(t) for t in self.union_types),\n              instance.__class__.__name__,\n              error_msg))\n\n    def match_type_variables(self, concrete_type):\n      sub_bindings = [\n          match_type_variables(t, concrete_type) for t in self.union_types\n          if is_consistent_with(concrete_type, t)\n      ]\n      if sub_bindings:\n        return {\n            var: Union[(sub[var] for sub in sub_bindings)]\n            for var in set.intersection(\n                *[set(sub.keys()) for sub in sub_bindings])\n        }","sourceCodeStart":537,"sourceCodeEnd":573,"githubUrl":"https://github.com/apache/beam/blob/12126d8942aaf848030c478b4c6a28c6af861c66/sdks/python/apache_beam/typehints/typehints.py#L537-L573","documentation":"UnionTypeConstraint.type_check raises CompositeTypeHintError when an instance matches none of the types in a Union hint. Beam tries each union member with check_constraint, collecting the last TypeError message, and if all fail it reports the allowed alternatives and the received instance's class.","triggerScenarios":"A value that is not any of Union[X, Y, ...] is passed to a transform typed with that Union, e.g. Union[int, float] receiving a str; also fires when a member's type_check raises TypeError for all alternatives (bad constraint params).","commonSituations":"Data pipelines where a field is 'int or float' but parsing yields str; None reaching a Union[int, float] (forgot to include Optional); version changes where a producer's return type shifted.","solutions":["Check the received type in the message and convert the value to one of the union's accepted types before the typed stage.","Widen the Union to include the actual type, e.g. Union[int, float, str], or use Optional[...] if None occurs.","Fix the producing transform to emit the declared type consistently.","Read the trailing error_msg for hints about why each alternative was rejected (e.g. an invalid member raising TypeError)."],"exampleFix":"# before\n.with_output_types(Union[int, float])  # produces '3.14' as str\n# after\n.with_output_types(Union[int, float]) and beam.Map(lambda x: float(x))\n# or widen: Union[int, float, str]","handlingStrategy":"type-guard","validationCode":"def matches_union(value, accepted=(int, float)):\n    return isinstance(value, accepted)","typeGuard":"def is_num_or_none(x):\n    return x is None or isinstance(x, (int, float))","tryCatchPattern":"try:\n    expand(pcoll)\nexcept CompositeTypeHintError as e:\n    if 'Expected an instance of one of' in str(e):\n        logger.error('value matches no Union member: %s', e)\n    raise","preventionTips":["Coerce values to a union member before typed stages","Include None via Optional when values can be absent","Keep producers and hints in sync with runtime type checks in tests"],"tags":["python","apache-beam","typehints","union"],"backgroundTag":"type-mismatch","analyzedSha":"12126d8942aaf848030c478b4c6a28c6af861c66","analyzedAt":"2026-09-13T01:50:10.254Z","contentChangedAt":"2026-09-13T01:50:10.254Z","schemaVersion":2},"datasetVersion":"2026-09-20T03:17:13.778Z"}