开发者

Python: callback when accessing the value of a variable?

开发者 https://www.devze.com 2023-01-18 05:05 出处:网络
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 func

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.

I开发者_StackOverflow中文版t 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.ProxyType does, 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.


Sounds like you want properties.

class DeepThought(object):

    @property
    def answer(self):
        print ("Computing the Ultimate Answer to the Ultimate Question"
                   " of Life, The Universe, and Everything ")
        return 42

print DeepThought().answer

You can do that only in classes.


Given your constraints, the only viable solution is to fork Python and modify its internal handling of variable lookups. You may also need to modify the bytecode definition. Be prepared for a performance hit.

Or write a PEP and be very, very patient. Your choice.


There are several implementations of poor-man's lazy evaluation in Python, such as lazypy.

True lazy evaluation is not available in CPython, of course, but is available in PyPy, using the thunk object space.


In that particular case, you can overload the __str__ method on the return type of f(). for example.

def f():
    class _f:
      def __str__(self):
        return "something"
    return _f()
0

精彩评论

暂无评论...
验证码 换一张
取 消