computation_utils.py 2.04 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Copyright 2019, The TensorFlow Federated Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Defines utility functions for constructing TFF computations."""

16
17
18
19
import collections

import attr

20
21
22
from tensorflow_federated.python.common_libs import py_typecheck


23
def update_state(state, **kwargs):
24
25
26
27
28
29
30
31
32
33
  """Returns a new `state` with new values for fields in `kwargs`.

  Args:
    state: the structure with named fields to update.
    **kwargs: the list of key-value pairs of fields to update in `state`.

  Raises:
    KeyError: if kwargs contains a field that is not in state.
    TypeError: if state is not a structure with named fields.
  """
34
  # TODO(b/129569441): Support Struct as well.
35
  if not (py_typecheck.is_named_tuple(state) or py_typecheck.is_attrs(state) or
36
          isinstance(state, collections.abc.Mapping)):
37
38
39
40
    raise TypeError('state must be a structure with named fields (e.g. '
                    'dict, attrs class, collections.namedtuple), '
                    'but found {}'.format(type(state)))
  if py_typecheck.is_named_tuple(state):
41
42
43
    # In Python 3.8 and later `_asdict` no longer return OrdereDict, rather a
    # regular `dict`.
    d = collections.OrderedDict(state._asdict())
44
45
46
  elif py_typecheck.is_attrs(state):
    d = attr.asdict(state, dict_factory=collections.OrderedDict)
  else:
47
    for key in kwargs:
48
49
50
51
      if key not in state:
        raise KeyError(
            'state does not contain a field named "{!s}"'.format(key))
    d = state
52
  d.update(kwargs)
53
  if isinstance(state, collections.abc.Mapping):
54
    return d
55
  return type(state)(**d)