Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add template method: shuffle #514

Merged
merged 2 commits into from Dec 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -0,0 +1 @@
"""Spook - Not your homie."""
@@ -0,0 +1,35 @@
"""Spook - Not your homie."""
from __future__ import annotations

from random import Random, shuffle
from typing import TYPE_CHECKING, Any, Iterable

from ....templating import AbstractSpookTemplateFunction

if TYPE_CHECKING:
from collections.abc import Callable


class SpookTemplateFunction(AbstractSpookTemplateFunction):
"""Spook template function to shuffle lists."""

name = "shuffle"

requires_hass_object = False
is_available_in_limited_environment = True
is_filter = True
is_global = True

def shuffle(self, items: Iterable[Any], seed: Any = None) -> Iterable[Any]:
"""Shuffle a list, either with a seed or without."""
items = list(items)
if seed:
r = Random(seed)
r.shuffle(items)
else:
shuffle(items)
return items

def function(self) -> Callable[..., Any]:
"""Return the python method that runs this template function."""
return self.shuffle