0

It's a bit like the singleton pattern with the twist that one passes arguments when acquiring the object and are getting the same object if and only if the arguments are the same. Example in python:

a = get_object(42)
b = get_object(42)
c = get_object(19)

a is b
a is not c
1
  • 2
    Perhaps you mean memoization? Commented Aug 22, 2024 at 13:57

2 Answers 2

0

Function having the following properties:

  • return values are identical for identical arguments (no variation with local static variables, non-local variables, mutable reference arguments or input streams, i.e., referential transparency)
  • has no side effects (no mutation of local static variables, non-local variables, mutable reference arguments or input/output streams).

Is called pure. For pure functions you can apply the memoization:

In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls to pure functions and returning the cached result when the same inputs occur again.

Sign up to request clarification or add additional context in comments.

Comments

0

In Python memoization is achievable

either via functools.cache:

from functools import cache

@cache
def get_object(id):
   pass

or via functools.lru_cache:

from functools import lru_cache

@lru_cache(maxsize=10)
def get_object(id):
  pass

Please bear in mind, these decorators do not work well with complex data structures like list.

In those cases you would receive an error like this:

TypeError: unhashable type: 'list'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.