Passing kwargs to a Language.factory #10606
-
I am writing a custom factory where users can specify a number of unconstrained keyword arguments in the config. However, I find that spaCy does not like such optional kwargs. import spacy
from spacy import Language
@Language.factory(
"custom_fctry"
)
class CustomFactory:
def __init__(self, nlp: Language, name: str, **kwargs):
self.nlp = nlp
self.name = name
self.rev_kwargs = {v: k for k, v in kwargs.items()}
nlp = spacy.load("en_core_web_sm")
nlp.add_pipe("custom_fctry", last=True) Error trace:
Of course, this is a dummy example. But is there any way to allow users to pass in custom kwargs that I in turn can pass through to other functions? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
So, theoretically, one could just use a dictionary here. import spacy
from spacy import Language
@Language.factory(
"custom_fctry"
)
class CustomFactory:
def __init__(self, nlp: Language, name: str, kwargs: dict):
self.nlp = nlp
self.name = name
self.rev_kwargs = {v: k for k, v in kwargs.items()}
# note the print statement here
print(self.rev_kwargs)
nlp = spacy.load("en_core_web_sm")
nlp.add_pipe("custom_fctry", last=True, config={"kwargs": {"hello": "world"}})
# {'world': 'hello'} But I'm a little more curious about the use case. Why would you want to pass down keyword arguments? You're also able to refer to functions from the spaCy config and that might be a more preferable abstraction in the long run. |
Beta Was this translation helpful? Give feedback.
-
Hey @koaning. My main goal is having this to be as user-friendly as possible. Having to specify an extra "dict" inside the config is not ideal - but if that is the way that it is intended, I can use that. The use case is that I initialize another object with the remaining given kwargs. These kwargs are not necessarily known beforehand, so I cannot specify the arguments manually.
I will use your suggestion, thanks. |
Beta Was this translation helpful? Give feedback.
-
For spaCy components, we typically put the factory decorator on a function instead of directly on the class. If you follow the same pattern, you can use a kwargs glob in the function and pass it to the class as a dict, which should allow your users flexibility while keeping the type checking machinery happy too. |
Beta Was this translation helpful? Give feedback.
For spaCy components, we typically put the factory decorator on a function instead of directly on the class. If you follow the same pattern, you can use a kwargs glob in the function and pass it to the class as a dict, which should allow your users flexibility while keeping the type checking machinery happy too.