spaCy - Span.set_extension Classmethod



This class method was introduced in version 2.0. It defines a custom attribute on the Span. Once done, that attribute will become available via Span._.

Arguments

The table below explains its arguments −

NAME TYPE DESCRIPTION
name Unicode This argument represents the name of the attribute to set by the extension. For example, ‘his_attr’ will be available as span._.his_attr.
default - It is the optional default value of the attribute for the case when no getter or method is defined.
method callable It is used to set a custom method on the object. For example, span._.compare(other_doc).
getter callable This attribute represents the getter function that will takes the object and will return an attribute value. It is mainly called when the user accesses the ._ attribute.
setter callable This attribute represents the Setter function that will take the Doc & a value and will modify the object. It is mainly called when the user writes to the Span._ attribute.
Force bool It will forcefully overwrite an existing attribute.

Example

An example of Span.set_extension class method is as follows −

import spacy
nlp_model = spacy.load("en_core_web_sm")
from spacy.tokens import Span
city = lambda span: any(city in doc.text for city in ("New York", "India", "USA"))
Span.set_extension("has_city", getter=city, force = True)
doc = nlp_model("I like India")
doc[0:3]._.has_city

Output

Upon execution, you will receive the following output −

True
spacy_container_span_class.htm
Advertisements