Skip to content
39 changes: 39 additions & 0 deletions dynamic_programming/use_effect_simulation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""
Simulation of a simple useEffect-like behavior in Python.

This demonstrates executing a function when a dependency changes.
Reference:
https://en.wikipedia.org/wiki/Reactive_programming
"""

from typing import Callable, Any

Check failure on line 9 in dynamic_programming/use_effect_simulation.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (I001)

dynamic_programming/use_effect_simulation.py:9:1: I001 Import block is un-sorted or un-formatted help: Organize imports

Check failure on line 9 in dynamic_programming/use_effect_simulation.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (UP035)

dynamic_programming/use_effect_simulation.py:9:1: UP035 Import from `collections.abc` instead: `Callable` help: Import from `collections.abc`


def use_effect_simulation(callback: Callable[[], None], dependency: Any) -> None:
"""
Executes the callback when the dependency changes.

>>> calls = []
>>> def cb():
... calls.append("called")
>>> use_effect_simulation(cb, 1)
>>> use_effect_simulation(cb, 1)
>>> use_effect_simulation(cb, 2)
>>> calls
['called', 'called']
"""
if not hasattr(use_effect_simulation, "_prev"):
use_effect_simulation._prev = None # type: ignore

Check failure on line 26 in dynamic_programming/use_effect_simulation.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (PGH003)

dynamic_programming/use_effect_simulation.py:26:45: PGH003 Use specific rule codes when ignoring type issues

if use_effect_simulation._prev != dependency:
callback()
use_effect_simulation._prev = dependency


if __name__ == "__main__":
def example():
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide return type hint for the function: example. If the function does not return a value, please provide the type hint as: def function() -> None:

As there is no test file in this pull request nor any test function or class in the file dynamic_programming/use_effect_simulation.py, please provide doctest for the function example

print("Effect triggered!")

use_effect_simulation(example, 1)
use_effect_simulation(example, 1)
use_effect_simulation(example, 2)

Check failure on line 39 in dynamic_programming/use_effect_simulation.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (W292)

dynamic_programming/use_effect_simulation.py:39:38: W292 No newline at end of file help: Add trailing newline
Loading