[Python-ideas] "Assignment expression" with function call-alike syntax

Kirill Balunov kirillbalunov at gmail.com
Tue May 22 17:32:36 EDT 2018


Just one more variation on "assignment exression" syntax to make the list
more complete :) Sorry, if something similar has already been suggested.
The idea is to use function's call-like syntax in the from: `this( name =
expr )`. I'm not sure that such idea will find its supporters and whether
it is possible to implement it in a general way, but nevertheless. Below is
a half- and slow-working prototype and some silly examples just for the
sake of feeling the idea:

import sys
import ctypes

def this(**assign):
    assert len(assign) == 1
    [(name, value)] = assign.items()
    frame = sys._getframe(1)
    frame.f_locals[name] = value
    ctypes.pythonapi.PyFrame_LocalsToFast(ctypes.py_object(frame),
                                          ctypes.c_int(0))
    return value

Loop-and-a-half example with `dummy` function[1]:

# in global scope everything works ok since locals is globals
>>> while len( this( val = dummy() ) ) >= 0:
...     print(val)
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
    ...


# needs to set the same local name to work inside function
def func():
    val = ...
    while len( this( val = dummy() ) ) >= 0:
        print(val)



>>> # relies on the implicit underlying function's local `x`
>>> [[this(x = (x+10)), x//10, x*10] for x in [100, 200, 300]]
[[110, 11, 1100], [210, 21, 2100], [310, 31, 3100]]


In this way it is somewhat possible to make an assignment in `while` and `if
` headers right now, which covers 90% cases, but it is damn slow. Maybe be
it is worth to make `this` magic call-alike object work fast...on the other
hand does anyone like `this`?


With kind regards,
-gdg

[1]:

def dummy(ls = [0]):
    ls.append(ls[-1]+1)
    return ls
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180523/71a16536/attachment.html>


More information about the Python-ideas mailing list