On 2020-01-30 7:17 p.m., Andrew Barnert via Python-ideas wrote:
On Jan 30, 2020, at 11:20, Johan Vergeer <johanverg...@gmail.com> wrote:
> ## Attribute names
>
> You should be able to get the name of an attribute.
>
> ```python
> class Foo:
> bar: str = "Hello"
>
> def __init__(self):
> self.baz = "World"
>
> def __str__(self):
> return f"{nameof(self.bar)}: {bar}, {nameof(self.baz): {baz}}" # Returns
"bar: Hello, baz: World"
>
> foo = Foo()
>
> nameof(foo) # Returns "foo"
> nameof(foo.bar) # Returns "bar"
If you compile nameof(foo.bar) to a function call, that function gets called with the
string "Hello". There’s no way you can get anything else out of that string at
runtime. (You can use horrible frame hacks to inspect the caller’s context and try to
guess what it was trying to pass you, which will work in many cases, but if you’re
proposing a new language feature why make it depend on that?)
What you want to compile this to is pretty clearly just the string “bar”. Which
is immediately available at compile time.
You do need to go through the whole grammar to decide exactly what productions
you should be able to use in a nameof and what the result should be. But that
shouldn’t be too hard. (And it’s a necessary first step toward an
implementation anyway.)
Consider:
x=nameof(foo.bar)
in today's python becomes:
foo.bar
x="bar"
and when running this you get an AttributeError or something.
the benefit is that "bar" is only typed once, and the attribute access
(and thus error-raising code) is tied to the resulting string. either
you change both the attribute access *and* the resulting string, or you
get an error. (correct me if I'm wrong.)
_______________________________________________
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/RJWWSGIWUJ4OUNQDSAK7JAGE2VSOJYRD/
Code of Conduct: http://python.org/psf/codeofconduct/