[Python-ideas] Delayed Execution via Keyword

Joseph Hackman josephhackman at gmail.com
Fri Feb 17 00:24:53 EST 2017


Howdy All!

This suggestion is inspired by the question on "Efficient debug logging".

I propose a keyword to mark an expression for delayed/lazy execution, for
the purposes of standardizing such behavior across the language.

The proposed format is:
delayed: <expr>
i.e. log.info("info is %s", delayed: expensiveFunction())

Unlike 'lambda' which returns a function (so the receiver must be
lambda-aware), delayed execution blocks are for all purposes values. The
first time the value (rather than location) is read, or any method on the
delayed object is called, the expression is executed and the delayed
expression is replaced with the result. (Thus, the delayed expression is
only every evaluated once).

Ideally:
a = delayed: 1+2
b = a
print(a) #adds 1 and 2, prints 3
# a and b are now both just 3
print(b) #just prints 3

Mechanically, this would be similar to the following:

class Delayed():
    def __init__(self, func):
        self.__func = func
        self.__executed = False
        self.__value = None

    def __str__(self):
        if self.__executed:
            return self.__value.__str__()
        self.__value = self.__func()
        self.__executed = True
        return self.__value.__str__()


def function_print(value):
    print('function_print')
    print(value)

def function_return_stuff(value):
    print('function_return_stuff')
    return value

function_print(function_return_stuff('no_delay'))

function_print(Delayed(lambda: function_return_stuff('delayed')))

delayed = Delayed(lambda: function_return_stuff('delayed_object'))
function_print(delayed)
function_print(delayed)

Unfortunately, due to
https://docs.python.org/3/reference/datamodel.html#special-lookup , this
magic delayed class would need to implement many magic methods, as
__getattribute__ is not _always_ called.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170217/845785a9/attachment.html>


More information about the Python-ideas mailing list