On Mon, Feb 3, 2020 at 3:58 AM Richard Damon <rich...@damon-family.org>
wrote:

>
> IF Python had a proper refactoring tool (see my other message where I
> question the ability to do that) then the nameof operator would clearly
> help keep logging/debug strings in line with the program definitions.
>
> A statement like print("bar", foo.bar) would be very hard to notice that
> the "bar" match the foo.bar, while
>
> print(nameof(foo.bar), foo.bar) makes the connection explicit.
>

What you're actually asking for is a way for a refactoring tool to
recognize that the string "bar" is a reference to the bar in foo.bar.
You're NOT asking for the Python compiler to recognize that. There are lots
of ways to do this. And Ricky Teachey's examples show that this is pretty
ugly.

On Mon, Feb 3, 2020 at 9:38 AM Ricky Teachey <ri...@teachey.org> wrote:

> To restate the motivation: the hope is that there is a potentially large
> benefit of being able to more easily refactor code with something like a
> nameof().
>
> <snip>
>
> class FunctionLogger:
>     # NOTE: this docstring will result in a runtime error, so can't even use 
> nameof() here to help ourselves
>     f"""Records use of a function.
>     The optional `{nameof(FunctionLogger.log)}` parameter is to be a callable 
> that accepts a string.
>     It is logging.info by default.
>     """
> *...*                logging.exception(f"failed to log {func_name!r} call; is 
> {cls_name}.{log_param_name} set correctly?")
>
> *Bottom line: refactoring remains a chore. The win is minimal. Do nothing
> option is preferred.*
>
> 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



>
_______________________________________________
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/J2DZZLAOV72SS4XXJISX7KPZNJPYUZVE/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to