CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-panel

The powerful data exploration & web app framework for Python.

Pending
Overview
Eval results
Files

parameter-integration.mddocs/

Parameter Integration

Integration with the Param library for creating reactive UIs from parameterized classes and managing parameter dependencies. This system enables automatic UI generation, reactive programming patterns, and seamless integration between Panel components and Param-based models.

Capabilities

Automatic UI Generation

Generate user interfaces automatically from parameterized classes with appropriate widgets for each parameter type.

class Param:
    """
    Auto-generate UI from Parameterized class with widgets for each parameter.
    
    Parameters:
    - object: Parameterized class instance to create UI for
    - parameters: List of parameter names to include (default: all)
    - widgets: Dict mapping parameter names to specific widget types
    - show_labels: Whether to show parameter labels
    - show_name: Whether to show the class name
    - **params: Additional parameters
    """

Reactive Expressions

Create reactive expressions that automatically update when parameter values change.

class ReactiveExpr:
    """
    Reactive expression component that updates automatically.
    
    Parameters:
    - object: Function or expression to evaluate reactively
    - **params: Additional parameters
    """

Parameter References

Reference and bind to specific parameters for creating reactive dependencies.

class ParamRef:
    """
    Parameter reference for creating reactive bindings.
    
    Parameters:
    - object: Parameterized object containing the parameter
    - parameter: Name of parameter to reference
    - **params: Additional parameters
    """

class ParamFunction:
    """
    Function parameter reference for method binding.
    
    Parameters:
    - function: Function to reference
    - **params: Additional parameters
    """

class ParamMethod:
    """
    Method parameter reference for instance method binding.  
    
    Parameters:
    - instance: Object instance containing the method
    - method: Method name to reference
    - **params: Additional parameters
    """

Usage Examples

Basic Parameter UI Generation

import panel as pn
import param

class Settings(param.Parameterized):
    """Application settings with various parameter types"""
    
    title = param.String(default="My App", doc="Application title")
    theme = param.Selector(default='light', objects=['light', 'dark'], doc="UI theme")
    max_items = param.Integer(default=100, bounds=(1, 1000), doc="Maximum items to display")
    enable_debug = param.Boolean(default=False, doc="Enable debug mode")
    refresh_rate = param.Number(default=1.0, bounds=(0.1, 10.0), doc="Refresh rate in seconds")
    created_date = param.Date(default=datetime.date.today(), doc="Creation date")
    
settings = Settings()

# Auto-generate UI from parameters
settings_ui = pn.Param(
    settings,
    parameters=['title', 'theme', 'max_items', 'enable_debug', 'refresh_rate'],
    widgets={
        'title': pn.widgets.TextInput,
        'refresh_rate': {'type': pn.widgets.FloatSlider, 'step': 0.1}
    },
    show_labels=True,
    show_name=True
)

Custom Widget Mapping

class DataAnalysis(param.Parameterized):
    
    dataset = param.Selector(default='iris', objects=['iris', 'titanic', 'boston'])
    columns = param.ListSelector(default=[], objects=[])
    plot_type = param.Selector(default='scatter', objects=['scatter', 'line', 'bar', 'histogram'])
    color_by = param.String(default='')
    
    @param.depends('dataset', watch=True)
    def _update_columns(self):
        # Update available columns based on dataset
        if self.dataset == 'iris':
            self.param.columns.objects = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
        # ... update for other datasets

analysis = DataAnalysis()

# Create UI with custom widgets
analysis_ui = pn.Param(
    analysis,
    widgets={
        'dataset': pn.widgets.RadioButtonGroup,
        'columns': pn.widgets.CheckBoxGroup,
        'plot_type': {'type': pn.widgets.Select, 'width': 200},
        'color_by': pn.widgets.AutocompleteInput
    }
)

Reactive Programming with Dependencies

import param
import pandas as pd
import matplotlib.pyplot as plt

class InteractivePlot(param.Parameterized):
    
    x_column = param.Selector()
    y_column = param.Selector() 
    color_column = param.Selector(default=None, allow_None=True)
    plot_type = param.Selector(default='scatter', objects=['scatter', 'line', 'bar'])
    
    def __init__(self, df, **params):
        self.df = df
        # Set parameter options from DataFrame columns
        columns = list(df.columns)
        self.param.x_column.objects = columns
        self.param.y_column.objects = columns
        self.param.color_column.objects = [None] + columns
        super().__init__(**params)
        
        # Set default values
        if len(columns) >= 2:
            self.x_column = columns[0]
            self.y_column = columns[1]
    
    @param.depends('x_column', 'y_column', 'color_column', 'plot_type')
    def create_plot(self):
        """Reactive method that updates when parameters change"""
        if not self.x_column or not self.y_column:
            return pn.pane.HTML("<p>Please select X and Y columns</p>")
        
        fig, ax = plt.subplots(figsize=(8, 6))
        
        if self.plot_type == 'scatter':
            scatter = ax.scatter(
                self.df[self.x_column], 
                self.df[self.y_column],
                c=self.df[self.color_column] if self.color_column else 'blue',
                alpha=0.6
            )
            if self.color_column:
                plt.colorbar(scatter, ax=ax, label=self.color_column)
                
        elif self.plot_type == 'line':
            ax.plot(self.df[self.x_column], self.df[self.y_column])
            
        elif self.plot_type == 'bar':
            ax.bar(self.df[self.x_column], self.df[self.y_column])
        
        ax.set_xlabel(self.x_column)
        ax.set_ylabel(self.y_column)
        ax.set_title(f'{self.plot_type.title()} Plot: {self.y_column} vs {self.x_column}')
        
        return pn.pane.Matplotlib(fig, tight=True)

# Create interactive plot
df = pd.read_csv('data.csv')
plot_app = InteractivePlot(df)

# Create reactive layout
layout = pn.Row(
    pn.Param(plot_app, width=300),
    plot_app.create_plot,
    sizing_mode='stretch_height'
)

Advanced Parameter Binding

class Dashboard(param.Parameterized):
    
    data_source = param.Selector(default='live', objects=['live', 'historical', 'simulated'])
    refresh_interval = param.Integer(default=5, bounds=(1, 60))
    auto_refresh = param.Boolean(default=True)
    
    def __init__(self, **params):
        super().__init__(**params)
        self.data = pd.DataFrame()
        self.setup_periodic_refresh()
    
    def setup_periodic_refresh(self):
        """Setup automatic data refresh based on parameters"""
        def refresh_data():
            if self.auto_refresh:
                self.data = self.fetch_data()
                return self.create_visualization()
            return pn.pane.HTML("<p>Auto-refresh disabled</p>")
        
        # Create periodic callback
        self.refresh_callback = pn.state.add_periodic_callback(
            refresh_data, 
            period=self.refresh_interval * 1000
        )
    
    @param.depends('data_source')
    def fetch_data(self):
        """Fetch data based on selected source"""
        if self.data_source == 'live':
            return self.get_live_data()
        elif self.data_source == 'historical':
            return self.get_historical_data()
        else:
            return self.generate_simulated_data()
    
    @param.depends('refresh_interval', watch=True)
    def update_refresh_rate(self):
        """Update periodic callback when refresh interval changes"""
        if hasattr(self, 'refresh_callback'):
            pn.state.remove_periodic_callback(self.refresh_callback)
            self.setup_periodic_refresh()
    
    def create_visualization(self):
        """Create visualization from current data"""
        if self.data.empty:
            return pn.pane.HTML("<p>No data available</p>")
        
        return pn.pane.DataFrame(self.data.head(10))

dashboard = Dashboard()

# Create UI with parameter controls and reactive display
app = pn.Column(
    "# Live Dashboard",
    pn.Param(dashboard, parameters=['data_source', 'refresh_interval', 'auto_refresh']),
    pn.bind(dashboard.create_visualization)
)

Parameter Validation and Constraints

class FormValidator(param.Parameterized):
    
    name = param.String(default="", regex=r'^[A-Za-z\s]+$')
    email = param.String(default="", regex=r'^[^@]+@[^@]+\.[^@]+$')
    age = param.Integer(default=18, bounds=(13, 120))
    password = param.String(default="")
    confirm_password = param.String(default="")
    
    @param.depends('password', 'confirm_password', watch=True)
    def validate_passwords(self):
        if self.password != self.confirm_password:
            self.param.confirm_password.constant = False
            # Show validation error
        else:
            self.param.confirm_password.constant = True
    
    def is_valid(self):
        """Check if all parameters are valid"""
        try:
            self.param.name.validate(self.name)
            self.param.email.validate(self.email)
            self.param.age.validate(self.age)
            return self.password == self.confirm_password and len(self.password) >= 8
        except ValueError:
            return False

validator = FormValidator()

# Create form with validation
form_ui = pn.Param(
    validator,
    widgets={
        'password': pn.widgets.PasswordInput,
        'confirm_password': pn.widgets.PasswordInput
    }
)

submit_button = pn.widgets.Button(name="Submit", button_type="primary")

def handle_submit(event):
    if validator.is_valid():
        pn.state.notifications.success("Form submitted successfully!")
    else:
        pn.state.notifications.error("Please fix validation errors")

submit_button.on_click(handle_submit)

form = pn.Column(form_ui, submit_button)

Integration with External APIs

class APIClient(param.Parameterized):
    
    api_key = param.String(default="")
    endpoint = param.Selector(default='users', objects=['users', 'posts', 'comments'])
    limit = param.Integer(default=10, bounds=(1, 100))
    
    @param.depends('api_key', 'endpoint', 'limit')
    def fetch_data(self):
        """Reactive method to fetch data from API"""
        if not self.api_key:
            return pn.pane.HTML("<p>Please provide API key</p>")
        
        try:
            # Simulate API call
            url = f"https://api.example.com/{self.endpoint}"
            params = {'limit': self.limit, 'key': self.api_key}
            # response = requests.get(url, params=params)
            # data = response.json()
            
            # Mock data for demonstration
            data = [{'id': i, 'name': f'Item {i}'} for i in range(self.limit)]
            
            return pn.pane.JSON(data, depth=2)
            
        except Exception as e:
            return pn.pane.HTML(f"<p>Error: {str(e)}</p>")

api_client = APIClient()

# Create API client interface
api_interface = pn.Column(
    "# API Data Viewer",
    pn.Param(api_client, parameters=['api_key', 'endpoint', 'limit']),
    pn.Divider(),
    api_client.fetch_data
)

Parameter Types and Widgets

Panel automatically maps parameter types to appropriate widgets:

  • param.StringTextInput
  • param.IntegerIntInput or IntSlider (with bounds)
  • param.NumberFloatInput or FloatSlider (with bounds)
  • param.BooleanCheckbox
  • param.SelectorSelect
  • param.ListSelectorMultiSelect
  • param.DateDatePicker
  • param.DateTimeDatetimePicker
  • param.RangeRangeSlider
  • param.ColorColorPicker

Custom widget mappings can override these defaults for specialized interfaces.

Install with Tessl CLI

npx tessl i tessl/pypi-panel

docs

authentication-system.md

chat-interface.md

core-functions.md

custom-components.md

index.md

layout-components.md

links-system.md

pane-system.md

parameter-integration.md

pipeline-system.md

template-system.md

widget-system.md

tile.json