How network collects objects created in "with" block?

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!