def get_opt_attr(obj_pyxb, attr_str, default_val=None):
    """Get an optional attribute value from a PyXB element.

    The attributes for elements that are optional according to the schema and
    not set in the PyXB object are present and set to None.

    PyXB validation will fail if required elements are missing.

    Args:
      obj_pyxb: PyXB object
      attr_str: str
        Name of an attribute that the PyXB object may contain.

      default_val: any object
        Value to return if the attribute is not present.

    Returns:
      str : Value of the attribute if present, else ``default_val``.

    """
    v = getattr(obj_pyxb, attr_str, default_val)
    return v if v is not None else default_val