Delayed execution for Python

submited by
Style Pass
2024-04-25 00:00:15

Subscriptions are the lifeblood of LWN.net. If you appreciate this content and would like to see more of it, your subscription will help to ensure that LWN continues to thrive. Please visit this page to join up and keep LWN on the net.

A discussion about more efficient debug logging on the python-ideas mailing list quickly morphed into thinking about a more general construct for Python: a delayed evaluation mechanism. The basic problem is that Python will fully evaluate arguments to functions even when they will end up being unused. That is always inefficient but may not seriously affect performance except for expensive argument calculations, where that inefficiency can really add up.

The discussion started with a post from Barry Scott, who was looking for a way to avoid the costly evaluation of arguments to a debug logging routine. The value of the arguments would never be used because debugging was disabled. He had code something like the following: debug = False def debuglog(msg): if debug: print('Debug: %s' % (msg,)) debuglog('Info: %s' % (expensive(),))

A way to avoid the call to expensive(), since the value would never be used, is what Scott was seeking. Several people suggested using lambda to create a "callable" object and to pass that to debuglog(): def debuglog(msg): if debug: if callable(msg): msg = msg() print('Debug: %s' % (msg,)) debuglog(lambda: 'Info: %s' % (expensive(),))

Leave a Comment