On 1/21/2020 4:50 PM, Eric V. Smith wrote:
On 1/21/2020 4:32 PM, Andrew Barnert via Python-ideas wrote:
What would the semantics of nameof be in Python? Would it just be lambda obj: obj.__name__? Or some fancy inspect-module style chain of “try this, then that, then the other”? Or does it need to look at the compiled source code context or something?
I think some wrapper around inspect.getmembers() would be the easiest/best thing to do.
dict(inspect.getmembers(obj))['__name__']
With some error checking for the KeyError if inspect.getmembers can't get a name for the object you passed in.
There are probably more performant ways to write this, but this was my easy one-liner version.
And in case it's not clear, my point is: Many things in Python don't have have names. For those that do, the inspect module knows about them, so use it. And if there's something that has a name that inspect currently doesn't recognize, then if we fix inspect to understand the name of that object, everyone who uses inspect would win. Eric