def Substitute(self, pattern):
    """Formats given pattern with this substitution environment.

    A pattern can contain placeholders for variables (`%%foo%%`) and scopes
    (`%%bar.baz%%`) that are replaced with concrete values in this substiution
    environment (specified in the constructor).

    Args:
      pattern: A pattern with placeholders to substitute.

    Returns:
      A pattern with placeholders substituted with concrete values.
    """
    if isinstance(pattern, bytes):
      substs = [re.escape(subst.encode("ascii")) for subst in self._substs]
      regex = re.compile(b"|".join(substs))

      def Replacement(match):
        key = match.group(0).decode("ascii")
        return self._substs[key].encode("utf-8")

    elif isinstance(pattern, Text):
      substs = [re.escape(subst) for subst in self._substs]
      regex = re.compile("|".join(substs))

      def Replacement(match):
        key = match.group(0)
        return self._substs[key]

    else:
      raise TypeError("Unexpected pattern type '{}'".format(type(pattern)))

    if not substs:
      return pattern
    else:
      return regex.sub(Replacement, pattern)