
On Sun, Apr 19, 2020 at 10:50 PM Alex Hall <alex.mojaki@gmail.com> wrote:
On Sun, Apr 19, 2020 at 5:59 PM David Mertz <mertz@gnosis.cx> wrote:
I think you've missed on alternative. Well, it's a variation on "status
quo": Use a silly magic helper function like my Q() or Alex' dict_of() in his sorcery library.
[...]
So no, this is not a problem that can be solved by a function in current Python.
On the other hand, we can change Python to make writing functions like that safe and easy. If code objects held a mapping from bytecode positions to AST nodes (which in turn would ideally know their source code, but that's not essential, e.g. it's not needed for the keyword argument stuff) then writing Q() and other neat magical functions (see the rest of sorcery for examples) would be relatively easy and reliable. And it would have other great applications, like making [tracebacks more detailed]( https://github.com/ipython/ipython/pull/12150). I'd be really excited about that, and I've thought about proposing it here before. But it might be opening Pandora's box, and I expect there'd be plenty of (probably valid) objections.
Exposing the AST is probably overkill, but we could probably come up with a different way to give Python users easy access to the argument names. For example, suppose you could define functions like this: ``` foo = 1 bar = 2 # Note the ***, different from ** def Q(***args_with_names): return args_with_names assert Q(foo, bar) == dict(foo=foo, bar=bar) def debug_print(***args_with_names): print(args_with_names) debug_print(foo, bar) # prints {"foo": 1, "bar": 2} ``` Then you would only need a few small instances of magical syntax. Most users would never need to know what `***` means. If they come across a function call like `func(**Q(foo, bar))`, they can at least tell that keyword arguments are being passed. And the function Q would be easy to google or inspect with help(Q) in the shell. The syntax for calls and dicts wouldn't need to be complicated further.