I would like a way to limit the calling of a function to once per values of parameters.
For example
JavaScript
x
10
10
1
def unique_func(x):
2
return x
3
4
>>> unique_func([1])
5
[1]
6
>>> unique_func([1])
7
*** wont return anything ***
8
>>> unique_func([2])
9
[2]
10
Any suggestions? I’ve looked into using memoization but not established a solution just yet.
This is not solved by the suggested Prevent a function from being called twice in a row since that only solves when the previous func call had them parameters.
Advertisement
Answer
Memoization uses a mapping of arguments to return values. Here, you just want a mapping of arguments to None
, which can be handled with a simple set.
JavaScript
1
14
14
1
def idempotize(f):
2
cache = set()
3
def _(x):
4
if x in cache:
5
return
6
cache.add(x)
7
return f(x)
8
return _
9
10
11
@idempotize
12
def unique_fun(x):
13
14
With some care, this can be generalized to handle functions with multiple arguments, as long as they are hashable.
JavaScript
1
9
1
def idempotize(f):
2
cache = set()
3
def _(*args, **kwargs):
4
k = (args, frozenset(kwargs.items()))
5
if k in cache:
6
return
7
return f(*args, **kwargs)
8
return _
9