On 16/09/2023 01:14, Chris Angelico wrote:
But if that tool can be taught that nameof indicates a variable name,
then it can rename inside it just like it would rename anything else.
It works already with existing tools that will treat "nameof(a+b)" as a function call, which it is syntactically but not semantically, so renaming b to c will now produce the string "a+c". I think my IDE does offer to do this with variable names in strings and comments, but it produces so many false hits I don't enjoy using the feature.
Your problem here is a limitation of the variable renaming tool. I'm
suggesting a solution to that problem. This is not a language problem,
it's an editor problem, so it needs an editor solution.
It needs language (parser) support because it does what you identified early on: "take whatever is given and put it in quotes", where "whatever is given" is the text of the expression only available at run-time. (Actually, I can think of something complicated one might possibly do with the text produced in exceptions, but please don't.)

Taking an example from my REPL just now (it happens that r2 is the AST of an Expression), you could simulate nameof with f-strings:

>>> f"{r2.body.op.test=}"
'r2.body.op.test=42'
>>> f"{r2.body.op.test=}".split('=')[0]
'r2.body.op.test'

This also evaluates the expression, encodes the result as text then discards it, which is undesirable. The point is that renaming r2, or the fields of a BinOp (if it were project-local, not a stdlib object) would cause the string to change in most existing IDEs.

Attempts to guess the name from the expression at runtime are futile and a red herring. Trying to describe the desired semantics that way leads to nonsensical ideas, I agree.

I'm not convinced this feature is widely useful. Here I'm just trying to focus us on the *viable* semantics MRAB identified.

--

Jeff Allen
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/RQISFW5UV2EW6ZB3ZKUDNV2R45MWIH3O/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to