def _python_int_to_bytes(py_int: int) -> bytes:
  """Encodes a vanilla Python integer into bytes.

  The output is a signed, big-endian byte string with as many bytes as needed to
  encode it without losing precision.
  NOTE: Only signed integers are accepted.

  Args:
    py_int: The integer to be encoded.
  Returns:
    The integer represented as bytes.
  """
  # Calculate the number of bytes needed to encode this _signed_ integer.
  # For example, to encode int(127) we need 7 // 8 + 1 == 1 byte. This is the
  # same as what we need to encode int(-127). However, to encode int(128) or
  # int(-128) we actually need 2 bytes.
  num_bytes_needed = py_int.bit_length() // 8 + 1
  return py_int.to_bytes(num_bytes_needed, byteorder='big', signed=True)