python type hints for spaCy

Viewed 696

I'm struggling to set type hints for anything involving spaCy types.

Trying to use the return types like "Language" and "Token" from the documentation of spaCy but they don't seem to work...I'm on python 3.8.5.

As an example say I have this:

import spacy

def load_lang() -> what_goes_here:
   return spacy.load("en_core_web_sm")

According to the docs this "Returns Language". I tried Language or spacy.Language with no luck. I have similar problems when working with tokens for example doing something like this:

return [token for token in doc if not token.is_stop]

Again docs mention "Returns Token" as the return object but I can't type hint it. I don't want to go down the List[str] from typing as I'm assuming it's the wrong way to go.

Any help will be much appreciated. Thank you in advance.

1 Answers

There should be no problem if you import Language class using:

from spacy.language import Language

and then use it as the type hint:

def load_lang() -> Language:
   return spacy.load("en_core_web_sm")
Related