Param
Declarative parameters for robust Python classes and a rich API for reactive programming
Install / Use
/learn @holoviz/ParamREADME
Param
Param is a zero-dependency Python library that provides two main features:
- Easily create classes with rich, declarative attributes -
Parameterobjects - that include extended metadata for various purposes such as runtime type and range validation, documentation strings, default values or factories, nullability, etc. In this sense, Param is conceptually similar to libraries like Pydantic, Python's dataclasses, or Traitlets. - A suite of expressive and composable APIs for reactive programming, enabling automatic updates on attribute changes, and declaring complex reactive dependencies and expressions that can be introspected by other frameworks to implement their own reactive workflows.
This combination of rich attributes and reactive APIs makes Param a solid foundation for constructing user interfaces, graphical applications, and responsive systems where data integrity and automatic synchronization are paramount. In fact, Param serves as the backbone of HoloViz’s Panel and HoloViews libraries, powering their rich interactivity and data-driven workflows.
Here is a very simple example showing both features at play. We declare a UserForm class with three parameters: age as an Integer parameter and and name as a String parameter for user data, and submit as an Event parameter to simulate a button in a user interface. We also declare that the save_user_to_db method should be called automatically when the value of the submit attribute changes.
import param
class UserForm(param.Parameterized):
age = param.Integer(bounds=(0, None), doc='User age')
name = param.String(doc='User name')
submit = param.Event()
@param.depends('submit', watch=True)
def save_user_to_db(self):
print(f'Saving user to db: name={self.name}, age={self.age}')
...
user = UserForm(name='Bob', age=25)
user.submit = True # => Saving user to db: name=Bob, age=25
Enjoying Param? Show your support with a Github star to help others discover it too! ⭐️
| | |
| --- | --- |
| Downloads |
| Build Status |
| Coverage |
|
| Latest dev release |
|
| Latest release |
|
| Python |
| Docs |
|
| Binder |
|
| Support |
|
Rich class attributes for runtime validation and more
Param lets you create classes and declare facts about each of their attributes through rich Parameter objects. Once you have done that, Param can handle runtime attribute validation (type checking, range validation, etc.) and more (documentation, serialization, etc.). Let's see how to use Parameter objects with a simple example, a Processor class that has three attributes.
import param
# Create a class by inheriting from Parameterized
class Processor(param.Parameterized):
# An Integer parameter that allows only integer values between 0 and 10,
# has a default of 3, and a custom docstring.
retries = param.Integer(default=3, bounds=(0, 10), doc="Retry attempts.")
# A Boolean parameter, False by default.
verbose = param.Boolean(default=False, doc="Emit progress messages.")
# A Selector parameter, with only two allowed values "fast" and "accurate",
# "fast" by default.
mode = param.Selector(
default="fast", objects=["fast", "accurate"],
doc="Execution strategy."
)
def run(self):
if self.verbose:
print(f"[{self.mode}] retry={self.retries}")
# ...main logic...
# You can of course override the default value on instantiation.
processor = Processor(verbose=True)
# A Parameterized instance behaves as a usual instance of a class.
processor.run()
# => [fast] retry=3
# Parameterized implements a nice and simple repr.
print(repr(processor))
# => Processor(mode='accurate', name='Processor00042', retries=3, verbose=False)
# Attempting to set the retries attribute to 42 will raise
# an error as the value must be between 0 and 10.
try:
processor.retries = 42
except ValueError as e:
print(e)
# => Integer parameter 'Processor.retries' must be at most 10, not 42.
# The `.param` namespace allows to get a hold on Parameter objects via
# indexing or attribute access.
print(processor.param['mode'].objects) # => ['fast', 'accurate']
print(processor.param.mode.objects) # => ['fast', 'accurate']
# This namespace offers many more useful methods, such as `.update()`
# to update multiple parameters at once, or `.values()` to obtain
# a dict of parameter name to parameter value.
processor.param.update(mode='accurate', verbose=False)
print(processor.param.values())
# => {'mode': 'accurate', 'name': 'Processor00042', 'retries': 3, 'verbose': False}
Runtime attribute validation is a great feature that helps build defendable code bases! Alternative libraries, like Pydantic and others, excel at input validation, and if this is only what you need, you should probably look into them. Where Param shines is when you also need:
- Attributes that are also available at the class level, allowing to easily configure a hierarchy of classes and their instances.
- Parameters with rich metadata (
default,doc,label,bounds, etc.) that downstream tooling can inspect to build configuration UIs, CLIs, or documentation automatically. - Parameterized subclasses that inherit Parameter metadata from their parents, and can selectively override certain attributes (e.g. overriding
defaultin a subclass).
Let's see this in action by extending the example above with a custom processor subclass:
class CustomProcessor(Processor):
# This subclass overrides the bounds of the `retries` Parameter
# and the default of the `verbose` Parameter. All the other
# Parameter metadata are inherited from Processor.
retries = param.Integer(bounds=(0, 100))
verbose = param.Boolean(default=True)
# Attributes exist at both the class-level and instance-level
print(CustomProcessor.verbose) # => True
# The `.param` namespace is also available at the class-level.
# Parameter metadata inheritance in action, with `default`
# inherited from Processor and `bounds` overridden by CustomProcessor.
print(CustomProcessor.param['retries'].default) # => 3
print(CustomProcessor.param['retries'].bounds) # => (0, 100)
# Class attributes are also runtime validated.
try:
CustomProcessor.retries = 200
except ValueError as e:
print(e)
# => Integer parameter 'CustomProcessor.retries' must be at most 100, not 200.
cprocessor = CustomProcessor()
# As in normal Python classes, class-level attribute values apply
# to all instances that didn't override it.
print(cprocessor.mode) # => 'fast'
Processor.mode = 'accurate'
print(cprocessor.mode) # => 'accurate'
Reactive Programming
Param extends beyond rich class attributes with a suite of APIs for reactive programming. Let's do a quick tour!
We'll start with APIs that trigger side-effects only, which either have the noun watch in their name or are invoked with watch=True:
<parameterized_obj>.param.watch(fn, *parameters, ...): Low-level, imperative API to attach callbacks to parameter changes, the callback receives one or more richEventobjects.@depends(*parameter_names, watch=True): In a Parameterized class, declare dependencies and automatically watch parameters for changes to call the decorated method.bind(fn, *references, watch=True, **kwargs): Function binding with automatic references (parameters, bound functions, reactive expressions) watching and triggering on changes.
import param
def debug_event(event: param.parameterized.Event):
print(event)
class SideEffectExample(param.Parameterized):
a = param.String()
b = param.String()
c = param.String()
def __init__(self, **params):
super().__init__(**params)
# We register the debug_event callback, that will be called when a changes.
self.param.watch(debug_event,
