Hello Python community,
Earlier this year I put forward a proposal for decorators on variables which I felt was well received in concept, but fell flat on the syntax. One of the responses to that thread was rather than abusing the decorator, to use a new symbol to get the target of an assignment statement as a string on the right hand side. I would call this compile-time reflection of assignment targets, or simply reflection. Although initially continuing on with my original syntax, the idea of using such a token in my own code came up on more than one occasion this year and I wanted to see what it might really look like.
From that, this proposal is to add a new token to Python, currently spelled <<<, which, at compile time, is replaced with the string representation of the nearest assignment target, either assignment statement or assignment expression. It does not bind with either keyword arguments or default parameters. Neither does it work in any kind of non-assignment binding. When encountered anywhere other than the right hand side of some assignment, it is an unconditional SyntaxError.
Having access to the target at runtime is most often useful in meta programming and the standard library has several factory functions that require the user to repeat the variable name in the function call to get expected behavior. Bellow are some examples of where I believe the reflection token would be used if adopted.
>>> Point = namedtuple(<<<, 'x, y, z')
>>> Point
<class '__main__.Point'>
>>> UUIDType = NewType(<<<, str)
>>> UUIDType
__main__.UUIDType
>>> class Colors(Enum):
... Black = <<<
... GRAY = <<<
... WHITE = <<<
...
>>> Colors.GRAY.value
'GRAY'
>>> HOME = '$' + <<<
>>> HOME
'$HOME'
>>> if error := response.get(<<<):
... if errorcode := error.get(<<<):
... print(f"Can't continue, got {errorcode=}")
...
Can't continue, got errorcode=13
To get a feel for using this new token I have created a fork of the 3.11 alpha that implements a *very* incomplete version of this new grammar, just enough to actually produce all of the examples above. It also passes a small new test suite with further examples https://github.com/ucodery/cpython/blob/reflection/Lib/test/test_reflection.py.