Pointer workaround in Python

I am building a dash application on top of huge amounts of data points. As I do not want to load all data every time I need them from disk (> 30m datapoints), I built a DataManager, managing the data. As the application has multiple scripts for each view, I passed the manager to each of them when switching the page.

Well, as Python is not C, Java nor Swift, it actually does not work with pointers. So is there a python-way to implement such a behavior without loading all data points when opening a site?

Here is my Python implementation so far:

dm = DataManager.DataManager()

@app.callback(Output('page-content', 'children'),
            [Input('url', 'pathname')])
def display_page(pathname):
    if pathname == '/runningmap':
        return RunningMap(dm)
    elif pathname == '/settings':
        return Settings(dm)
    else:
        return RunningMap(dm)

Answer

In Python, all objects are pass-by-reference. If you want to pass something elsewhere and still let the caller mutate it afterwards, you can use a list containing a single element as if it’s a pointer.

class Foo:

  def __init__(a):
    self.a = a

  def p():
    print(self.a)


a_ptr = [1]
foo = Foo(a_ptr)
foo.p()
a_ptr[0] += 1
foo.p()

would print

1
2

Leave a Reply

Your email address will not be published. Required fields are marked *