def from_attributes(cls: Type[T], **field_values) -> T:
    """Directly instantiates a struct given all of its fields.

    Structs can override ``__init__`` to have arbitrary custom behavior, but
    this may make it difficult to construct new instances of structs with
    particular field values. This function makes it possible to directly
    instantiate an instance of a struct with given attributes.

    (Note: Overriding ``__init__`` in a ``Struct`` subclass is usually
    discouraged.)

    The main purpose of this method is to enable easier serialization and
    deserialization of structs. Callers of this method are responsible for
    maintaining any invariants expected by the class.

    Args:
      **field_values: Values for each of the struct's fields.

    Returns:
      A new instance of the class.
    """
    # Make sure our fields are correct.
    expected_fields = dataclasses.fields(cls)  # pytype: disable=wrong-arg-types
    expected_names = set(field.name for field in expected_fields)
    given_names = set(field_values.keys())
    if expected_names != given_names:
      raise ValueError(
          "Incorrect fields provided to `from_attributes`; expected"
          f" {expected_names}, got {given_names}"
      )
    # Make a new object, bypassing the class's initializer.
    value = object.__new__(cls)
    # Set all the attributes, bypassing the class's __setattr__.
    for k, v in field_values.items():
      object.__setattr__(value, k, v)
    return value
Directly instantiates a struct given all of its fields.

    Structs can override ``__init__`` to have arbitrary custom behavior, but
    this may make it difficult to construct new instances of structs with
    particular field values. This function makes it possible to directly
    instantiate an instance of a struct with given attributes.

    (Note: Overriding ``__init__`` in a ``Struct`` subclass is usually
    discouraged.)

    The main purpose of this method is to enable easier serialization and
    deserialization of structs. Callers of this method are responsible for
    maintaining any invariants expected by the class.

    Args:
      **field_values: Values for each of the struct's fields.

    Returns:
      A new instance of the class.
    
penzai/core/struct.py