[Python-ideas] Another use case for the 'lazy' (aka 'delayed') keyword

M.-A. Lemburg mal at egenix.com
Tue Feb 28 12:30:22 EST 2017


On 28.02.2017 17:54, M.-A. Lemburg wrote:
> On 28.02.2017 17:35, David Mertz wrote:
>> Clearly there is SOME semantics that is consistent and coherent since many
>> languages have either a lazy or eager declaration syntax, with different
>> defaults between languages but both being built in.  There are a lot of
>> ways that Python isn't Haskell, obviously.  But both Scheme and OCaml are
>> eager by default with a lazy declaration (and Haskell or Miranda have an
>> eager declaration correspondingly).
>>
>> It might be worth looking at their semantics in the PEP.
> 
> Scheme, for example, uses an explicit approach to turning
> a promise into a value:
> 
> http://www.shido.info/lisp/scheme_lazy_e.html
> 
> This makes a lot of sense, but you can already have the
> same in Python using generators.

Here's an example similar to OCaml's lazy evaluation, which
uses a simple lazy proxy object.

import sys
import time

### OCaml like lazy evaluation

class Lazy:
    def __init__(self, code, frame):
        self.code = code
        self.globals = frame.f_globals
        self.locals = frame.f_locals
    def force(self):
        return eval(self.code, self.globals, self.locals)

def lazy(code):
    return Lazy(code, sys._getframe(1))

###

def log(level, b, c):
    if level > 100:
        return
    if isinstance(c, Lazy):
        c = c.force()
    print ('%04i: %s' % (level, b % c))

def expensive(x):
    time.sleep(2.0)
    return x

value = 1
log(1000, 'Hello %i', lazy("expensive(value)"))
log(10, 'Error %i', lazy("expensive(value)"))

###

Everything is nice and explicitly defined in the example.
You can see where the deferred evaluation is requested
and where it's eventually run. There are no surprises.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Experts (#1, Feb 28 2017)
>>> Python Projects, Coaching and Consulting ...  http://www.egenix.com/
>>> Python Database Interfaces ...           http://products.egenix.com/
>>> Plone/Zope Database Interfaces ...           http://zope.egenix.com/
________________________________________________________________________

::: We implement business ideas - efficiently in both time and costs :::

   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611
               http://www.egenix.com/company/contact/
                      http://www.malemburg.com/



More information about the Python-ideas mailing list