Skip to content

Commit

Permalink
feat(task): add an indentity Task factory
Browse files Browse the repository at this point in the history
Add a factory method on the `Task` class, `sghi.task.Task.of_indentity`.
This returns identity `Task` instances that always return their input
argument as is when invoked.
  • Loading branch information
kennedykori committed Apr 11, 2024
1 parent d30daab commit 77ddf67
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/sghi/task/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
ThreadPoolExecutor,
wait,
)
from functools import reduce, update_wrapper
from functools import cache, reduce, update_wrapper
from logging import Logger, getLogger
from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast, final, overload

Expand Down Expand Up @@ -284,6 +284,23 @@ def of_callable(source_callable: Callable[[_IT], _OT]) -> Task[_IT, _OT]:
# FIXME: rename 'source_callable' to 'target_callable' instead.
return _OfCallable(source_callable=source_callable)

@staticmethod
@cache
def of_identity() -> Task[_IT, _IT]:
"""Return a :class:`~sghi.task.Task` that always returns its input.
The returned ``Task`` always returns its input argument as is.
.. note::
The instances returned by this method are NOT guaranteed to be
distinct on each invocation.
:return: A ``Task`` instance that always returns its input argument
as is.
"""
return _OfCallable(source_callable=lambda _v: _v)


# =============================================================================
# COMMON IMPLEMENTATIONS
Expand Down
14 changes: 14 additions & 0 deletions test/sghi/task_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -675,3 +675,17 @@ def test_of_callable_method_returns_expected_value(self) -> None:

assert add_100(-100) == task1(-100) == 0
assert multiply_by_10(100) == task2(100) == 1000

def test_of_identity_method_returns_expected_value(self) -> None:
"""
:meth:`Task.of_identity` should return a ``Task`` instance that always
returns its input value as is.
"""

a_reference: list[int] = list(range(5))

assert isinstance(Task.of_identity(), Task)
assert Task.of_identity()(5) == 5
assert Task.of_identity()("Hello, World!!") == "Hello, World!!"
assert Task.of_identity()(None) is None
assert Task.of_identity()(a_reference) is a_reference

0 comments on commit 77ddf67

Please sign in to comment.