How network collects objects created in "with" block?

Hi there,

I’m new to Nengo, and I’ve just read the below example code:

   network = nengo.Network()
   with network:
       with nengo.Network(label="Vision"):
           v1 = nengo.Ensemble(n_neurons=100, dimensions=2)
       with nengo.Network(label="Motor"):
           sma = nengo.Ensemble(n_neurons=100, dimensions=2)
       nengo.Connection(v1, sma)

But I don’t understand how does the network collects the Ensemble objects created in the “with” block.
I can’t find the specific function do this work. Can anyone tell me how does these ensembles been added to the networks?

Thanks.

Hi @hongchf, welcome to the forum!

The with syntax uses Python’s context manager protocol, which allows us to do some additional steps in the nengo.Ensemble initialization depending on the context that it’s in. The exact way in which it works is a bit complicated and distributed across a few different Nengo classes, so I’ll do my best to explain the sequence of events.

  1. When you do with network, Network.__enter__ is called, which adds that network to the top of the Network.context stack.
  2. When you call nengo.Ensemble, a slightly different sequence of events happens than happens with a normal object due to the use of a metaclass, NetworkMember. NetworkMember.__call__ is what actually ends up happening, which reads the value of add_to_container and calls Network.add when add_to_container is True.
  3. Network.add adds the passed in object to the network that is on top of the Network.context stack.

Hopefully that helps!

Thank you @tbekolay, I understand it now.

1 Like