For a project I am working on, I have a param.Dataframe that can be updated and modified, or even replaced (through syncing with a database). I would then have multiple different Parameterized instances that draw data from this dataframe. Is there a way that I can sync this base dataframe across all those objects? i.e. can they all share a single instance of the dataframe? Or is the only way to use param.watch options?
I asked a similar question before here: Can a paramterized class react to parameters outside of itself?
You can pass parameterized classes (like a dataframe) into other parameterized classes (some random component) and react to them.
import param
import numpy as np
import pandas as pd
class Data(param.Parameterized):
df = param.DataFrame(df)
class Component1(param.Parameterized):
data = param.Parameterized()
@param.depends('data.df')
def view(self):
return self.data.df.sum().sum()
class Component2(param.Parameterized):
data = param.Parameterized()
@param.depends('data.df')
def view(self):
return len(self.data.df)
data = Data(df = pd.DataFrame(np.random.rand(10,10)))
# Have components that take the dataframe as a parameter
c1 = Component1(data=data)
c2 = Component2(data=data)
# Components have access to dataframe
print(c1.view(), c2.view())
#Update dataframe
data.df = pd.DataFrame(np.random.rand(100,100))
# Have it show up in all other components
print(c1.view(), c2.view())
Cool, this makes sense and is really helpful! I’m also wondering if there’s a way to set it so it’s possible to call @param.depends(‘data’) rather than @param.depends(‘data.df’)?
Not as far as I know. param.depends
reacts to parameters, not parameterized classes. You have to specify which parameters you want to depend on when using param.depends
.
Interestingly, you can just omit the param.depends
entirely from your methods, and each one will react all parameters declared in the class without having to specify which. Refer to: What is the purpose of @param.depends in a parameterized class?
Actually, this may not be true. By setting param.depends('data')
I seem to get the same functionality.