Using @network_operation with external variables (without passing them as global variables)

Description of problem

I’m trying to use @network_operation to change an external variable at every time step. However, per the Brian documentation : " The function being decorated should either have no arguments, or a single argument which will be called with the current time t ."

So the way I’m doing it is to pass the external variable as a global variable. Is there a better way to do this ? (since global variables are usually bad practice in Python)

Minimal code to reproduce problem

global var

var = 0

@network_operation(dt = 1*ms)
def f():
global var
var += 1

net = Network(f)

net.run(10*ms)

What you have aready tried

Tried to think about possible solutions but didn’t find any. Not sure if possible, just wondering. Thank you !

Probably the best solution is to create a class that will store your variable, and then create a NetworkOperation on a method of that class. Something like the following code (untested):

class MyFunc:
  def __init__(self):
    self.var = 0
  def run(self):
    self.var += 1
    ...

net_func = NetworkOperation(MyFunc().run, dt=1*ms)

More info here: NetworkOperation class — Brian 2 2.4.2 documentation

Thanks will try it out!

Just to add another potential solution: you can also “abuse” a container type to store the variable, e.g.:

var = [0]

@network_operation(dt = 1*ms)
def f():
  var[0] += 1

net = Network(f)

net.run(10*ms)
1 Like