code: def _custom_getter(
      getter: Callable[[Any], Any],
      classes: Optional[Iterable[Type[Any]]] = None,
      instances: Optional[Iterable[Any]] = None,
  ) -> ContextManager[Any]:
      """Applies the given `getter` when getting members of given `classes`.
  
      For example:
      >>> class X:
      ...   values = [1, 2]
  
      >>> x = X()
      >>> x.values
      [1, 2]
  
      >>> with _custom_getter(lambda x: x + [3], classes=[X]):
      ...   x.values
      [1, 2, 3]
  
      >>> with _custom_getter(lambda x: x + [3], instances={x}):
      ...   x.values
      [1, 2, 3]
  
      >>> x.values
      [1, 2]
  
      Args:
        getter: A callable to apply to each element of the class members.
        classes: The classes in which the getter is applied. If `None`, defaults to
          `set(o.__class__ for o in instances)`. If `classes and `instances` are
          both `None`, defaults to `[Module]`.
        instances: The instances in which the getter is applied. If `None`, the
          getter will apply in all instances of `classes`.
  
      Returns:
        A context manager in which the custom getter is active.
      """
      # Workaround for the fact that we can't annotate the type as `Collection` in
      # Python < 3.6.
      if instances is not None:
          instances = frozenset(instances)
  
      if classes is None:
          if instances is None:
              classes = _DEFAULT_CLASSES
          else:
              classes = frozenset(o.__class__ for o in instances)
  
      stack = contextlib.ExitStack()
  
      for cls in classes:
          orig_getattribute = (
              cls.__getattribute__
          )  # pytype: disable=attribute-error
  
          def new_getattribute(
              obj, name, orig_getattribute=orig_getattribute
          ):
              attr = orig_getattribute(obj, name)
  
              if (instances is None) or (obj in instances):
                  return getter(attr)
              else:
                  return attr
  
          stack.enter_context(
              _patch_getattribute(cls, new_getattribute)
          )
  
      return stack
  
file_path: sonnet/sonnet/src/custom_getter.py
imports: from typing import Any, Callable, ContextManager, Iterable, Optional, Type
  import contextlib
  from sonnet.src import base
  import tensorflow
  import tree
label_desc: Use image node_id 2 for calling a global function with example usage: _custom_getter(getter, classes, instances) and returns: stack, getter, attr