0

I have a class that initiates as:

MorrisLecarElectricField(external_field=lambda t:0, soma_current=lambda t:0, dend_current=lambda t:0, p=0.5, dt=0.1)

However, if I want to instantiate a bunch of these like such:

neurons = [MLEF.MorrisLecarElectricField(soma_current=lambda t: e) for e in np.arange(0, 200, 10)]

some funky pass by reference seems to be happening. I end up with a list of MorrisLecarElectricField objects that all have soma_current of lambda t: 190.

From what I understand lambdas do something funky with remembering the scope they were created in. Anybody have any idea how to sidestep this issue?

aznpwnzor
  • 11
  • 1
  • 2
  • Thanks for confirming my suspicions that it is a scoping issue. However, I'd still like to see if there are solutions that preserve the way I'm instantiating. EDIT: Nevermind, I see that default parameters solves it. – aznpwnzor Aug 28 '15 at 17:39
  • As answered in the linked question, you force the scope to resolve at declaration by using a default parameter, e.g. `soma_current=lambda t=e: t`. – TigerhawkT3 Aug 28 '15 at 17:41
  • Yep, thanks! Just to clarify my intentions, in this case, it would be actually be `soma_current=lambda t, e=e: e` since the real motivation is eventually to pass more complicated inputs like `soma_current=lambda t, e=e: e*np.sin(t)` – aznpwnzor Aug 28 '15 at 17:45
  • You would create a default parameter for any variable that you'd like to see resolved when the function is created rather than when the function is called. – TigerhawkT3 Aug 28 '15 at 17:50

0 Answers0