spaCy icon indicating copy to clipboard operation
spaCy copied to clipboard

Extension set inside for loop is not visible outside

Open dvaosta opened this issue 8 years ago • 3 comments

Hi, I have the following code:

for token in doc:
    if token.pos_ in pos_mapping.keys():
        token.set_extension('synsets', wn.synsets(token.text, pos=pos_mapping[token.pos_], lang='ita'))
    else:
        token.set_extension('synsets', [])
    print('first loop', token.text, token._.synsets)

for token in doc:
    print('second loop', token.text, token._.synsets)`

The print() inside the first loop correctly give the list of synsets (for words that have synsets), whereas the print in the other loop always return an empty list. How is this possible?

dvaosta avatar Apr 24 '18 13:04 dvaosta

UPDATE: in reality, the problem i that only the last value is retained and returned for all tokens. And this happens also if instead of setting the default I use a getter or a method, and it happens for any data type (string, int etc.).

dvaosta avatar Apr 25 '18 13:04 dvaosta

It looks like the problem in your code is that you're registering the extension on each individual token, instead of only once on the global object. I think what you were trying to do instead was to assign a value to your custom extension. For example:

from spacy.tokens import Token

Token.set_extension('synsets', default=False)  # register globally once

for token in doc:
    if token.pos_ in pos_mapping.keys():
        token._.synsets = 'some value'  # assign the value here

A more elegant solution would be to use a getter function that takes the token and returns a value for it. This should work especially well in your case, since you're using a the token's text and part-of-speech tag to generate the value. If you're using a getter, you won't have to iterate over your tokens and set each value manually – and the value will only be computed when you need it. For example:

from spacy.tokens import Token

def synsets_getter(token):
    if token.pos_ in pos_mapping.keys():
        return wn.synsets(token.text, pos=pos_mapping[token.pos_], lang='ita')
    return []

Token.set_extension('synsets', getter=synsets_getter)

Your tokens will now all have a ._.synsets attribute that uses your synsets_getter function to generate it, based on the tokens attributes.

You can find more details and examples of this in the docs on custom extension attributes.

ines avatar Apr 28 '18 13:04 ines

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

lock[bot] avatar May 28 '18 14:05 lock[bot]