[Python-ideas] Delayed Execution via Keyword

Steven D'Aprano steve at pearwood.info
Sat Feb 18 06:39:38 EST 2017

Using "delayed" in function signatures:

On Fri, Feb 17, 2017 at 09:27:35PM -0800, David Mertz wrote:

> That said, I think you are right that it makes no sense to declare a
> function signature with 'delayed' (or 'lazy', 'deferred', whatever word).

It makes perfect sense! That gives us function defaults which are 
evaluated only the first time they are needed, instead of when the 
function is defined.

def function(spam, eggs=delayed nth_prime(10**9)):

would be equivalent to:

def function(spam, eggs=None):
    if eggs is None:
        if _CACHED_DEFAULT is None:
            _CACHED_DEFAULT = nth_prime(10**9)
        return _CACHED_DEFAULT

I've done this in real life, e.g. to set up an expensive lookup table. 
The caller might provide their own, but if not, the function has its own 
default, where I want to delay generating the default until it is 
actually needed.


More information about the Python-ideas mailing list