Constraints API Reference

Constraint

class textattack.constraints.Constraint(compare_against_original)[source]

An abstract class that represents constraints on adversial text examples. Constraints evaluate whether transformations from a AttackedText to another AttackedText meet certain conditions.

Parameters:

compare_against_original (bool) – If True, the reference text should be the original text under attack. If False, the reference text is the most recent text from which the transformed text was generated. All constraints must have this attribute.

call_many(transformed_texts, reference_text)[source]

Filters transformed_texts based on which transformations fulfill the constraint. First checks compatibility with latest Transformation, then calls _check_constraint_many

Parameters:
  • transformed_texts (list[AttackedText]) – The candidate transformed AttackedText’s.

  • reference_text (AttackedText) – The AttackedText to compare against.

check_compatibility(transformation)[source]

Checks if this constraint is compatible with the given transformation. For example, the WordEmbeddingDistance constraint compares the embedding of the word inserted with that of the word deleted. Therefore it can only be applied in the case of word swaps, and not for transformations which involve only one of insertion or deletion.

Parameters:

transformation – The Transformation to check compatibility with.

extra_repr_keys()[source]

Set the extra representation of the constraint using these keys.

To print customized extra information, you should reimplement this method in your own constraint. Both single-line and multi- line strings are acceptable.

PreTransformationConstraint

class textattack.constraints.PreTransformationConstraint[source]

An abstract class that represents constraints which are applied before the transformation.

These restrict which words are allowed to be modified during the transformation. For example, we might not allow stopwords to be modified.

check_compatibility(transformation)[source]

Checks if this constraint is compatible with the given transformation. For example, the WordEmbeddingDistance constraint compares the embedding of the word inserted with that of the word deleted. Therefore it can only be applied in the case of word swaps, and not for transformations which involve only one of insertion or deletion.

Parameters:

transformation – The Transformation to check compatibility with.

extra_repr_keys()[source]

Set the extra representation of the constraint using these keys.

To print customized extra information, you should reimplement this method in your own constraint. Both single-line and multi- line strings are acceptable.