Suppose a function f() returns a value of arbitrary type, perhaps an object but possibly even a builtin type like int or list. Is there a way to assign a variable to that return value, and have a function of my choosing be called the first time the variable is used?
I suppose this is similar to lazy evaluation except that a reference to x exists and can be used by subsequent code.
It might look like this:
x = f() # f is a function, assign variable to return value, but return value is unknown
# do something arbitrary with x
return str(x) # this calls a callback attached to x, which returns the value of x to be used
Again, I want to do this on any type, not just an object instance.
If you want to write a C extension for it, you could wrap the value in something that behaves the way that Python’s
weakref.ProxyTypedoes, only with laziness instead of “weak”ness. You can always take a look at the Python source code to see how that’s done but something tells me it’s nontrivial.The implementation of the weakref proxy type in Python is here.