[Python-ideas] Delayed Execution via Keyword

Pavol Lisy pavol.lisy at gmail.com
Fri Feb 17 10:02:28 EST 2017

On 2/17/17, Chris Angelico <rosuav at gmail.com> wrote:

> Do delayed-expressions have identities or only values? For example:
> rand = delayed: random.randrange(10)
> otherrand = rand
> assert rand is otherrand # legal?
> randid = id(rand) # legal?
> print(rand) # force to concrete value
> assert any(rand is x for x in range(10)) # CPython int caching
> assert randid == id(rand) # now what?
> Alternatively, once the value becomes concrete, the delayed-expression
> becomes a trampoline/proxy to the actual value. Its identity remains
> unchanged, but all attribute lookups would be passed on to the other
> object. That does mean a permanent performance penalty though -
> particularly if it's doing it all in Python code rather than some sort
> of quick C bouncer.

what about:

    lazy_string = delayed: f"{fnc()}"

could it be possible?

BTW I was also thinking about something like l-strings (aka lazy
f-string) to solve this problem:

    logger.debug("format {expensive()}")

Still not sure if it is a good idea but with something like this:

    class Lazy_String:
        ''' this is only quick and dirty test implementation! '''

        def __init__(self, string=None):
            if string is None:
                self.body = "'None'"
                self.body = compile('f'+repr(string), "<lazy_string>", 'eval')
        def __sub__(self, string):
            return self
        def __str__(self):
            return eval(self.body)
        def __repr__(self):
            return self.__str__()

    lazy = Lazy_String()

we could use this:

    from lazy_string import lazy as l

    logger.debug(l-"format {expensive()}")  # kind of l-string without
new syntax

More information about the Python-ideas mailing list