Skip to content

Parameters

albert.collections.parameters.ParameterCollection

ParameterCollection(*, session: AlbertSession)

Bases: BaseCollection

Manage Parameters in the Albert platform.

A Parameter (ID format PRM..., e.g. "PRM9999999") is the definition of a single condition or input variable used when running experiments, such as Temperature, Spin Speed, or Instrument. It is often called an "indirect variable": the Parameter itself only names the variable, and its actual value and unit are fixed to a setpoint later, inside a Workflow.

Parameters are the building blocks of Parameter Groups (ParameterGroup) and form the parameter side of Data Templates (DataTemplate).

This collection is accessed as client.parameters.

Example

from albert import Albert
client = Albert()
param = client.parameters.get_by_id(id="PRM9999999")
param.name
# 'Temperature'

Parameters:

Name Type Description Default
session AlbertSession

The authenticated Albert session used for API calls.

required

Attributes:

Name Type Description
base_path str

The base API route for parameter requests.

Methods:

Name Description
create

Create a new parameter.

get_or_create

Return the existing parameter matching by name, or create it.

get_by_id

Get a single parameter by its ID.

get_by_ids

Get many parameters by their IDs.

get_all

Search for parameters by name or ID.

search

Search for parameters using free text and advanced filters.

update

Update an existing parameter.

delete

Delete a parameter by its ID.

Parameters:

Name Type Description Default
session AlbertSession

The authenticated Albert session used for API calls.

required
Source code in src/albert/collections/parameters.py
def __init__(self, *, session: AlbertSession):
    """Initialize a ParameterCollection.

    Parameters
    ----------
    session : AlbertSession
        The authenticated Albert session used for API calls.
    """
    super().__init__(session=session)
    self.base_path = f"/api/{ParameterCollection._api_version}/parameters"

base_path

base_path = (
    f"/api/{ParameterCollection._api_version}/parameters"
)

get_by_id

get_by_id(*, id: ParameterId) -> Parameter

Get a single parameter by its ID.

To find parameters without knowing their IDs, use get_all.

Example

param = client.parameters.get_by_id(id="PRM9999999")
param.name
# 'Temperature'

Parameters:

Name Type Description Default
id ParameterId

The Parameter ID (format PRM..., e.g. "PRM9999999").

required

Returns:

Type Description
Parameter

The fully populated parameter.

Source code in src/albert/collections/parameters.py
@validate_call
def get_by_id(self, *, id: ParameterId) -> Parameter:
    """Get a single parameter by its ID.

    To find parameters without knowing their IDs, use [`get_all`][albert.collections.parameters.ParameterCollection.get_all].

    !!! example
        ```python
        param = client.parameters.get_by_id(id="PRM9999999")
        param.name
        # 'Temperature'
        ```

    Parameters
    ----------
    id : ParameterId
        The Parameter ID (format ``PRM...``, e.g. ``"PRM9999999"``).

    Returns
    -------
    Parameter
        The fully populated parameter.
    """
    url = f"{self.base_path}/{id}"
    response = self.session.get(url)
    return Parameter(**response.json())

get_by_ids

get_by_ids(*, ids: list[ParameterId]) -> list[Parameter]

Get many parameters by their IDs.

Arbitrarily long ID lists are supported. Use this instead of repeated get_by_id calls when you already have several Parameter IDs to fetch. To find parameters without knowing their IDs, use get_all.

Example

params = client.parameters.get_by_ids(ids=["PRM9999999", "PRM2"])

Parameters:

Name Type Description Default
ids list[ParameterId]

The Parameter IDs to retrieve (format PRM...).

required

Returns:

Type Description
list[Parameter]

The parameters matching the provided IDs. Order is not guaranteed to match input IDs, and unknown IDs are omitted.

Source code in src/albert/collections/parameters.py
@validate_call
def get_by_ids(self, *, ids: list[ParameterId]) -> list[Parameter]:
    """Get many parameters by their IDs.

    Arbitrarily long ID lists are supported. Use this instead of repeated
    [`get_by_id`][albert.collections.parameters.ParameterCollection.get_by_id]
    calls when you already have several Parameter IDs to fetch. To find
    parameters without knowing their IDs, use [`get_all`][albert.collections.parameters.ParameterCollection.get_all].

    !!! example
        ```python
        params = client.parameters.get_by_ids(ids=["PRM9999999", "PRM2"])
        ```

    Parameters
    ----------
    ids : list[ParameterId]
        The Parameter IDs to retrieve (format ``PRM...``).

    Returns
    -------
    list[Parameter]
        The parameters matching the provided IDs. Order is not guaranteed
        to match input IDs, and unknown IDs are omitted.
    """
    if not ids:
        return []
    batches = [ids[i : i + 100] for i in range(0, len(ids), 100)]
    return [parameter for batch in batches for parameter in self.get_all(ids=batch)]

create

create(*, parameter: Parameter) -> Parameter

Create a new parameter.

This registers a new condition or input variable (e.g. Temperature or Spin Speed) that can then be used in Parameter Groups and Data Templates. To avoid creating duplicates when a parameter of the same name may already exist, use get_or_create instead.

Example

from albert.resources.parameters import Parameter
param = client.parameters.create(parameter=Parameter(name="Spin Speed"))
param.id
# 'PRM9999999'

Parameters:

Name Type Description Default
parameter Parameter

The parameter to create. Only name is required.

required

Returns:

Type Description
Parameter

The newly created parameter, populated with its assigned Parameter ID.

Source code in src/albert/collections/parameters.py
def create(self, *, parameter: Parameter) -> Parameter:
    """Create a new parameter.

    This registers a new condition or input variable (e.g. Temperature or Spin
    Speed) that can then be used in Parameter Groups and Data Templates. To
    avoid creating duplicates when a parameter of the same name may already
    exist, use [`get_or_create`][albert.collections.parameters.ParameterCollection.get_or_create] instead.

    !!! example
        ```python
        from albert.resources.parameters import Parameter
        param = client.parameters.create(parameter=Parameter(name="Spin Speed"))
        param.id
        # 'PRM9999999'
        ```

    Parameters
    ----------
    parameter : Parameter
        The parameter to create. Only ``name`` is required.

    Returns
    -------
    Parameter
        The newly created parameter, populated with its assigned Parameter ID.
    """
    response = self.session.post(
        self.base_path,
        json=parameter.model_dump(by_alias=True, exclude_none=True, mode="json"),
    )
    return Parameter(**response.json())

get_or_create

get_or_create(*, parameter: Parameter) -> Parameter

Return the existing parameter matching by name, or create it.

Matches an existing parameter by exact name. If a match is found, it is returned unchanged; otherwise a new parameter is created via create. Use this to avoid creating duplicate parameters.

Example

from albert.resources.parameters import Parameter
param = client.parameters.get_or_create(parameter=Parameter(name="Temperature"))
param.id
# 'PRM9999999'

Parameters:

Name Type Description Default
parameter Parameter

The parameter to get or create. Matched on name.

required

Returns:

Type Description
Parameter

The existing or newly created parameter.

Source code in src/albert/collections/parameters.py
def get_or_create(self, *, parameter: Parameter) -> Parameter:
    """Return the existing parameter matching by name, or create it.

    Matches an existing parameter by exact ``name``. If a match is found, it is
    returned unchanged; otherwise a new parameter is created via [`create`][albert.collections.parameters.ParameterCollection.create].
    Use this to avoid creating duplicate parameters.

    !!! example
        ```python
        from albert.resources.parameters import Parameter
        param = client.parameters.get_or_create(parameter=Parameter(name="Temperature"))
        param.id
        # 'PRM9999999'
        ```

    Parameters
    ----------
    parameter : Parameter
        The parameter to get or create. Matched on ``name``.

    Returns
    -------
    Parameter
        The existing or newly created parameter.
    """
    for match in self.get_all(names=parameter.name, exact_match=False):
        if match.name == parameter.name:
            logging.warning(
                f"Parameter with name {parameter.name} already exists. Returning existing parameter."
            )
            return match
    return self.create(parameter=parameter)

delete

delete(*, id: ParameterId) -> None

Delete a parameter by its ID.

This permanently removes the parameter.

Example

client.parameters.delete(id="PRM9999999")

Parameters:

Name Type Description Default
id ParameterId

The Parameter ID to delete (format PRM...).

required

Returns:

Type Description
None
Source code in src/albert/collections/parameters.py
@validate_call
def delete(self, *, id: ParameterId) -> None:
    """Delete a parameter by its ID.

    This permanently removes the parameter.

    !!! example
        ```python
        client.parameters.delete(id="PRM9999999")
        ```

    Parameters
    ----------
    id : ParameterId
        The Parameter ID to delete (format ``PRM...``).

    Returns
    -------
    None
    """
    url = f"{self.base_path}/{id}"
    self.session.delete(url)

search

search(
    *,
    text: str | None = None,
    ids: ParameterId | list[ParameterId] | None = None,
    created_by: str | list[str] | None = None,
    data_template: str | list[str] | None = None,
    parameter_group: str | list[str] | None = None,
    contains_field: str | list[str] | None = None,
    contains_text: str | list[str] | None = None,
    source_field: str | list[str] | None = None,
    additional_field: str | list[str] | None = None,
    translation: str | list[str] | None = None,
    metadata_filters: dict[str, Any] | None = None,
    custom_fields: dict[str, Any] | None = None,
    order_by: OrderBy = DESCENDING,
    sort_by: str | None = None,
    max_items: int | None = None,
) -> Iterator[ParameterSearchItem]

Search for parameters matching the given filters.

Returns lightweight, partially populated results. Results are returned as a lazily paginated iterator, so iterating fetches additional pages on demand. With no filters, searches across all accessible parameters.

Example

hits = client.parameters.search(text="temperature", max_items=10)
for hit in hits:
    print(hit.id, hit.name)

Parameters:

Name Type Description Default
text str

Free-text query matched against parameter fields.

None
ids ParameterId or list[ParameterId]

Filter by Parameter ID(s) (format PRM...).

None
created_by str or list[str]

Filter by creator display name(s).

None
data_template str or list[str]

Filter by data template name(s).

None
parameter_group str or list[str]

Filter by parameter group name(s).

None
contains_field str or list[str]

Field(s) to apply a contains search to.

None
contains_text str or list[str]

Text value(s) for the contains search.

None
source_field str or list[str]

Restrict which fields are included in each search result.

None
additional_field str or list[str]

Additional fields to include on each search result.

None
translation str or list[str]

Translation(s) to include in the search.

None
metadata_filters dict[str, Any]

Filter by custom field (metadata) values, keyed by field name. For string fields, map the name to a list of values, for example {"batchCode": ["B-100"]}. Multiple values on one field match any of them; different fields must all match.

None
custom_fields dict[str, Any]

Custom field type definitions used to interpret metadata_filters, keyed by field name, for example {"batchCode": "string"}.

None
order_by OrderBy

Sort direction. Default OrderBy.DESCENDING.

DESCENDING
sort_by str

Attribute to sort results by.

None
max_items int

Maximum number of items to return in total. If None, iterates over all matches.

None

Returns:

Type Description
Iterator[ParameterSearchItem]

A lazily paginated iterator of matching parameter search results.

Source code in src/albert/collections/parameters.py
@validate_call
def search(
    self,
    *,
    text: str | None = None,
    ids: ParameterId | list[ParameterId] | None = None,
    created_by: str | list[str] | None = None,
    data_template: str | list[str] | None = None,
    parameter_group: str | list[str] | None = None,
    contains_field: str | list[str] | None = None,
    contains_text: str | list[str] | None = None,
    source_field: str | list[str] | None = None,
    additional_field: str | list[str] | None = None,
    translation: str | list[str] | None = None,
    metadata_filters: dict[str, Any] | None = None,
    custom_fields: dict[str, Any] | None = None,
    order_by: OrderBy = OrderBy.DESCENDING,
    sort_by: str | None = None,
    max_items: int | None = None,
) -> Iterator[ParameterSearchItem]:
    """Search for parameters matching the given filters.

    Returns lightweight, partially populated results. Results are returned as a lazily
    paginated iterator, so iterating fetches additional pages on demand. With no filters,
    searches across all accessible parameters.

    !!! example
        ```python
        hits = client.parameters.search(text="temperature", max_items=10)
        for hit in hits:
            print(hit.id, hit.name)
        ```

    Parameters
    ----------
    text : str, optional
        Free-text query matched against parameter fields.
    ids : ParameterId or list[ParameterId], optional
        Filter by Parameter ID(s) (format ``PRM...``).
    created_by : str or list[str], optional
        Filter by creator display name(s).
    data_template : str or list[str], optional
        Filter by data template name(s).
    parameter_group : str or list[str], optional
        Filter by parameter group name(s).
    contains_field : str or list[str], optional
        Field(s) to apply a contains search to.
    contains_text : str or list[str], optional
        Text value(s) for the contains search.
    source_field : str or list[str], optional
        Restrict which fields are included in each search result.
    additional_field : str or list[str], optional
        Additional fields to include on each search result.
    translation : str or list[str], optional
        Translation(s) to include in the search.
    metadata_filters : dict[str, Any], optional
        Filter by custom field (metadata) values, keyed by field name. For string fields,
        map the name to a list of values, for example ``{"batchCode": ["B-100"]}``.
        Multiple values on one field match any of them; different fields must all match.
    custom_fields : dict[str, Any], optional
        Custom field type definitions used to interpret ``metadata_filters``, keyed by
        field name, for example ``{"batchCode": "string"}``.
    order_by : OrderBy, optional
        Sort direction. Default ``OrderBy.DESCENDING``.
    sort_by : str, optional
        Attribute to sort results by.
    max_items : int, optional
        Maximum number of items to return in total. If None, iterates over all matches.

    Returns
    -------
    Iterator[ParameterSearchItem]
        A lazily paginated iterator of matching parameter search results.
    """
    payload: dict[str, Any] = {
        "text": text,
        "albertId": ensure_list(ids),
        "order": order_by,
        "sortBy": sort_by,
        "createdBy": ensure_list(created_by),
        "dataTemplate": ensure_list(data_template),
        "parameterGroup": ensure_list(parameter_group),
        "containsField": ensure_list(contains_field),
        "containsText": ensure_list(contains_text),
        "sourceField": ensure_list(source_field),
        "additionalField": ensure_list(additional_field),
        "translation": ensure_list(translation),
    }
    if metadata_filters is not None:
        payload["metadataFilters"] = {"metadata": metadata_filters}
    if custom_fields is not None:
        payload["customFields"] = {"metadata": custom_fields}

    return AlbertPaginator(
        mode=PaginationMode.SEARCH_AFTER,
        path=f"{self.base_path}/search",
        session=self.session,
        method="POST",
        retry_safe=True,
        json=payload,
        max_items=max_items,
        deserialize=lambda items: [
            ParameterSearchItem(**item)._bind_collection(self) for item in items
        ],
    )

get_all

get_all(
    *,
    ids: list[ParameterId] | None = None,
    names: str | list[str] = None,
    exact_match: bool = False,
    order_by: OrderBy = DESCENDING,
    start_key: str | None = None,
    max_items: int | None = None,
) -> Iterator[Parameter]

Search for parameters, optionally filtered by name or ID.

Results are returned as a lazily paginated iterator, so iterating fetches additional pages on demand. With no filters, iterates over all parameters.

Example

for param in client.parameters.get_all(names="Temperature", max_items=10):
    print(param.id, param.name)

Parameters:

Name Type Description Default
ids list[ParameterId]

Restrict results to these Parameter IDs (format PRM...).

None
names str or list[str]

One or more parameter names to filter by.

None
exact_match bool

When True, only parameters whose name matches names exactly are returned. When False (default), name matching is partial.

False
order_by OrderBy

Sort direction. Default OrderBy.DESCENDING.

DESCENDING
start_key str

Pagination key to resume from. Usually left unset.

None
max_items int

Maximum number of items to return in total. If None, iterates over all matches.

None

Returns:

Type Description
Iterator[Parameter]

A lazily paginated iterator of parameters matching the given criteria.

Source code in src/albert/collections/parameters.py
@validate_call
def get_all(
    self,
    *,
    ids: list[ParameterId] | None = None,
    names: str | list[str] = None,
    exact_match: bool = False,
    order_by: OrderBy = OrderBy.DESCENDING,
    start_key: str | None = None,
    max_items: int | None = None,
) -> Iterator[Parameter]:
    """Search for parameters, optionally filtered by name or ID.

    Results are returned as a lazily paginated iterator, so iterating fetches
    additional pages on demand. With no filters, iterates over all parameters.

    !!! example
        ```python
        for param in client.parameters.get_all(names="Temperature", max_items=10):
            print(param.id, param.name)
        ```

    Parameters
    ----------
    ids : list[ParameterId], optional
        Restrict results to these Parameter IDs (format ``PRM...``).
    names : str or list[str], optional
        One or more parameter names to filter by.
    exact_match : bool, optional
        When True, only parameters whose name matches ``names`` exactly are
        returned. When False (default), name matching is partial.
    order_by : OrderBy, optional
        Sort direction. Default ``OrderBy.DESCENDING``.
    start_key : str, optional
        Pagination key to resume from. Usually left unset.
    max_items : int, optional
        Maximum number of items to return in total. If None, iterates over all
        matches.

    Returns
    -------
    Iterator[Parameter]
        A lazily paginated iterator of parameters matching the given criteria.
    """

    def deserialize(items: list[dict]) -> Iterator[Parameter]:
        yield from (Parameter(**item) for item in items)

    params = {
        "orderBy": order_by,
        "parameters": ids,
        "startKey": start_key,
    }
    params["name"] = ensure_list(names)
    params["exactMatch"] = exact_match

    return AlbertPaginator(
        mode=PaginationMode.KEY,
        path=self.base_path,
        session=self.session,
        params=params,
        max_items=max_items,
        deserialize=deserialize,
    )

update

update(*, parameter: Parameter) -> Parameter

Update an existing parameter.

Fetch the parameter (e.g. with get_by_id), modify the updatable fields on the returned object, then pass it here. Only the fields listed in Notes are applied; changes to other fields are ignored.

Example

param = client.parameters.get_by_id(id="PRM9999999")
param.name = "Bath Temperature"
updated = client.parameters.update(parameter=param)
updated.name
# 'Bath Temperature'

Parameters:

Name Type Description Default
parameter Parameter

The parameter to update. Must have a valid id.

required

Returns:

Type Description
Parameter

The updated parameter.

Notes

The following fields can be updated: metadata, name.

Source code in src/albert/collections/parameters.py
def update(self, *, parameter: Parameter) -> Parameter:
    """Update an existing parameter.

    Fetch the parameter (e.g. with [`get_by_id`][albert.collections.parameters.ParameterCollection.get_by_id]), modify the updatable
    fields on the returned object, then pass it here. Only the fields listed in
    Notes are applied; changes to other fields are ignored.

    !!! example
        ```python
        param = client.parameters.get_by_id(id="PRM9999999")
        param.name = "Bath Temperature"
        updated = client.parameters.update(parameter=param)
        updated.name
        # 'Bath Temperature'
        ```

    Parameters
    ----------
    parameter : Parameter
        The parameter to update. Must have a valid ``id``.

    Returns
    -------
    Parameter
        The updated parameter.

    Notes
    -----
    The following fields can be updated: ``metadata``, ``name``.
    """
    existing = self.get_by_id(id=parameter.id)
    payload = self._generate_patch_payload(
        existing=existing,
        updated=parameter,
    )
    payload_dump = payload.model_dump(mode="json", by_alias=True)
    for i, change in enumerate(payload_dump["data"]):
        if not self._is_metadata_item_list(
            existing_object=existing,
            updated_object=parameter,
            metadata_field=change["attribute"],
        ):
            change["operation"] = "update"
            if "newValue" in change and change["newValue"] is None:
                del change["newValue"]
            if "oldValue" in change and change["oldValue"] is None:
                del change["oldValue"]
            payload_dump["data"][i] = change
    if len(payload_dump["data"]) == 0:
        return parameter
    for e in payload_dump["data"]:
        self.session.patch(
            f"{self.base_path}/{parameter.id}",
            json={"data": [e]},
        )
    return self.get_by_id(id=parameter.id)