[Python-ideas] Light-weight call-by-name syntax in Python

Stephan Houben stephanh42 at gmail.com
Fri Feb 17 05:22:25 EST 2017


Proposal: Light-weight call-by-name syntax in Python

  The following syntax
     a : b
  is to be interpreted as:
     a(lambda: b)

Effectively, this gives a "light-weight macro system" to Python,
since it allows with little syntax to indicate that the argument to
a function is not to be immediately invoked.

It is a generalization of special-case syntax proposals like
 delayed: <expr>
In this proposal, `delayed' can be a normal callable.

Motivating examples follow:

# Logging
# The following assumes the logging library has been extended to support
# a callable argument in addition to a string.

import logging
logging.debug: "I have a %s" % expensive_function()

# Spawn parallel tasks
# This would work with the existing concurrent.futures unmodified.

from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(max_workers=4)
future = executor.submit: some_long_running_function(another_long_one())

# Asyncio

loop.call_soon_threadsafe: do_something(42)

# Custom asserts

from some_module_implementing_contracts import precondition

def foo(x):
    precondition: x >= 0
    return math.sqrt(x)


# Lazy evaluation

class delayed:
    def __init__(self, callback):
        self.callback = callback
        self.value = None

    def __call__(self):
        if self.callback is not None:
            self.value = self.callback()
            self.callback = None
        return self.value

promise = delayed: a() + b()
print(promise())


# default dictionary

dd = collections.defaultdict: MyDefaultObject(42)
print(dd["foo"])
# => prints MyDefaultObject(42)


Notes on syntax:
a : b is my preferred syntax.
It would conflict with existing use of : in a few places, e.g.
in if and while. My preferred approach is that we would
need to write (a : b) there.

An alternative is a as-yet-unused token such as :: .

Stephan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170217/58d3899a/attachment.html>


More information about the Python-ideas mailing list