def test_getattr_call_named(self, placement): federated_comp_named = computation_building_blocks.Reference( 'test', computation_types.FederatedType([('a', tf.int32), ('b', tf.bool), tf.int32], placement, True)) self.assertEqual(str(federated_comp_named.type_signature.member), '<a=int32,b=bool,int32>') name_a = computation_constructing_utils.construct_federated_getattr_call( federated_comp_named, 'a') name_b = computation_constructing_utils.construct_federated_getattr_call( federated_comp_named, 'b') self.assertIsInstance(name_a.type_signature, computation_types.FederatedType) self.assertIsInstance(name_b.type_signature, computation_types.FederatedType) self.assertEqual(str(name_a.type_signature.member), 'int32') self.assertEqual(str(name_b.type_signature.member), 'bool') type_utils.check_federated_value_placement( value_impl.to_value(name_a, None, context_stack_impl.context_stack), placement) type_utils.check_federated_value_placement( value_impl.to_value(name_b, None, context_stack_impl.context_stack), placement) with self.assertRaisesRegex(ValueError, 'has no element of name c'): _ = computation_constructing_utils.construct_federated_getattr_call( federated_comp_named, 'c')
def __getattr__(self, name): py_typecheck.check_type(name, six.string_types) if (isinstance(self._comp.type_signature, computation_types.FederatedType) and isinstance(self._comp.type_signature.member, computation_types.NamedTupleType)): return ValueImpl( computation_constructing_utils.construct_federated_getattr_call( self._comp, name), self._context_stack) elif not isinstance(self._comp.type_signature, computation_types.NamedTupleType): raise TypeError( 'Operator getattr() is only supported for named tuples, but the ' 'object on which it has been invoked is of type {}.'.format( str(self._comp.type_signature))) if name not in dir(self._comp.type_signature): raise AttributeError( 'There is no such attribute as \'{}\' in this tuple.'.format(name)) if isinstance(self._comp, computation_building_blocks.Tuple): return ValueImpl(getattr(self._comp, name), self._context_stack) return ValueImpl( computation_building_blocks.Selection(self._comp, name=name), self._context_stack)
def test_federated_getattr_call_fails_value(self): x = computation_building_blocks.Reference( 'x', computation_types.to_type([('x', tf.int32)])) with self.assertRaises(TypeError): computation_constructing_utils.construct_federated_getattr_call( value_impl.to_value(x), 'x')