Dependency injection in Gluon blocks


I’m trying to solve the following problem. I want to create a Gluon Block that depends on user-provided Block. I.e. in constructor it takes another Block. Think of seq2seq model that allows to provide custom encoders. Just passing already created Block in constructor is not ideal, because the passed Block would end up having “wrong” name scope.

My workaround for this is applying lazy Block creation. Instead of passing already created Block, I could pass a callable that creates it (e.g. partial(Block, **args). This is a slight annoyance for my Block’s users though.

Can you think of any better solution of this problem?


This depends on what you’re trying to do in the internals of your own Block. You should be able to pass an already created Block in the constructor, set it to a variable and use the forward of the already-created user defined Block in the forward function of your Block. Did this not work for you?

Can you post a snippet of your own Block to see how you’re currently using the callable that creates the block?


It works, obviously. The only annoyance is that the passed Block is not created under proper name scope. It might not seem like a big deal but it can be a source of confusion and I’d rather avoid it.


Ah I see. I can’t really think of a less cumbersome solution than the one you already have with the callable.