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.
- When you do
with network
,Network.__enter__
is called, which adds that network to the top of theNetwork.context
stack. - When you call
nengo.Ensemble
, a slightly different sequence of events happens than happens with a normalobject
due to the use of a metaclass,NetworkMember
.NetworkMember.__call__
is what actually ends up happening, which reads the value ofadd_to_container
and callsNetwork.add
whenadd_to_container
isTrue
. -
Network.add
adds the passed in object to the network that is on top of theNetwork.context
stack.
Hopefully that helps!