Home > Mobile >  How to best track variables in python and how to pass them by reference?
How to best track variables in python and how to pass them by reference?

Time:07-21

I have a small simulation written in python, in which the same variables are repeatedly changed with time. For debugging and visualization, I want to keep track of the values of some of these variables. The way it's done at the moment is with one list per variable, to which the current value is appended every:

x = 0
x_list = []
while t < 1:
    ...
    x_list.append(x)
print(x_list)

Doing this with every variable becomes very cumbersome and repetitive. What I'd like to do instead is to have this encapsulated in a tracker class, which I initialize once by telling it which variables to keep track of, and has a function to read all tracked variables and store them:

class Tracker():
    def __init__(self,variables):
        self.variables = variables
        self.track_values = []
        for v in variables:
            self.track_values.append([])
    
    def add_values(self):
        for t,v in zip(self.track_values, self.variables):
            t.append(get_value_of(v))

tracker = Tracker([...]) # Pass a list of variable references here

In other languages (like C), I'd pass the variable's pointer as argument, but I haven't found a satisfactory way to replicate this in python. Passing the variable name as a string would be an option I'm aware of, but it seems to be highly discouraged in other places. Is there a better, or more pythonic, way of doing this?

CodePudding user response:

you can use the vars() built-in which returns all of the variables and their values and just log the values at every timestep

print(vars())

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}

a=0

print(vars())

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 0}
  • Related