简体   繁体   中英

accessing a value from within a function

I'm trying to access a value from within a function ideally without making it global or calling the function again. I also can't use 'return' as the function is used by a class from a different library for a periodic call back.

The function below reads in data from a CSV (which is periodically being updated), does all the necessary transforms then uses a function called 'stream' that essentially updates a dataframe with only the new data points. As can be seen below, I tried setting attributes for the values I'm trying to access - that is, 'y_range_start' and 'y_range_end'. Finally the add_periodic_callback calls the update function every 1000ms to update the dataframe, and finally it's plotted (using Bokeh).

However, in order to keep the axes updated I need to access the 'y_range_start/end' from within the function to update the figure that resides outside of the 'update' function.

Accessing it as an attribute doesn't work (method mentioned above) as I need to call the function first ie update() \\n update.y_range_start - this is a problem as I don't want to be calling the update() function which will run the other lines above it again. I also can't use the return value, as the update function is designed specifically to work with add_periodic_callback.

It's been drilled into me not to use Global variables...

What other options do I have?

Thanks in advance!

def update():
    MAU_ios = pd.read_csv('myapp/data/pplus_ios_data.csv')
    MAU_ios['Date'] = pd.to_datetime(MAU_ios['Date'])
    MAU_ios['Vol'] = MAU_ios.Vol.astype(int)

    new_MAU_ios = {'Date':MAU_ios['Date'], 'Vol':MAU_ios['Vol']}

    source_ios.stream(new_MAU_ios)

    update.y_range_start = MAU_ios['Date'].min()
    update.y_range_end = MAU_ios['Date'].max()

curdoc().add_periodic_callback(update, 1000)

You could wrap it inside a class (this code won't work out of the box, but you can use it as a starting point):

class MyFancyWrapper:
    def __init__(self, source_ios):
        self.source_ios = source_ios
        # And other stuff you might need, e.g. for `update_y_axes`

    def update(self):
        MAU_ios = pd.read_csv('myapp/data/pplus_ios_data.csv')
        MAU_ios['Date'] = pd.to_datetime(MAU_ios['Date'])
        MAU_ios['Vol'] = MAU_ios.Vol.astype(int)

        new_MAU_ios = {'Date': MAU_ios['Date'], 'Vol': MAU_ios['Vol']}

        self.source_ios.stream(new_MAU_ios)

        self.update_y_axes(MAU_ios['Date'].min(), MAU_ios['Date'].max())

    def update_y_axes(self, start, end):
        print(start)
        print(end)


wrapper = MyFancyWrapper(source)
curdoc().add_periodic_callback(wrapper.update, 1000)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM