On 2020-02-04 3:33 a.m., Bruce Leban wrote:
Here is a much more readable alternative which has the advantage that it is already supported by Python. I'm going to show a harder example where I want to reference foo.bar and allow both foo and bar to be refactored. Here's the original proposal:
f"The field {nameof(foo)}.{nameof(foo.bar)} can be refactored."
Here's my alternative:
f"""The field {"foo.bar"} can be refactored."""
Since there's no real reason that you'd use {}around a literal string, we have our refactoring tool recognize that syntax as a variable reference. It has no net effect on the running code. If we don't want foo to be refactored, we write instead:
f"""The field foo.{"bar"} can be refactored."""
And if we just want the string to reference "bar" but want to make sure it's foo.bar not something_else.bar, we could write this:
f"""The field {"foo" and "bar"} can be refactored."""
--- Bruce
Huh I didn't think of using string literals in fstrings like that. (altho, are "raw" fstrings a thing?) Anyway, I like how we've all been focusing on refactoring but how about this use-case instead: let's say one has a function that takes an object and an attribute name because Reasons: def create_attr(obj, attr): setattr(obj, attr, Thing(attr)) def screw_attr(obj, attr): getattr(obj, attr)._reset() delattr(obj, attr) class Foo: def __init__(self): create_attr(self, nameof self.__mangled) def bar(self): screw_attr(self, nameof self.__mangled) there's currently no way to get a string representation of a mangled attr and a nameof operator would let you do so.
_______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-leave@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/J2DZZL... Code of Conduct: http://python.org/psf/codeofconduct/