On Jan 21, 2020, at 10:48, Johan Vergeer <johanverg...@gmail.com> wrote: > > I have worked with both C# and Python for a while now and there is one > feature of C# I'm missing in the Python language. > > This feature is the "nameof" operator. > (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/nameof). > The place I use this the most in C# is in `ToString()` methods or logging > messages. > This makes sure the developer cannot forget to update the name of a member. > > As an example I created this `Person` class. > > ``` > class Person: > def __init__(self, name, age): > self.name = name > self.age = age > > def __repr__(self): > return f"Person(name: {self.name}, age: {self.age})" > ``` > > With the `nameof` operator this would look like the following: > > ``` > class Person: > def __init__(self, name, age): > self.name = name > self.age = age > > def __repr__(self): > return f"{nameof(Person)}({nameof(self.name)}: {self.name}, > {nameof(self.age)}: {self.age})"
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? Unless it’s the last one, can’t this just be a normal function rather than a special operator? And if so, why does it need to be in the stdlib, much less a builtin, rather than just a function you stick in your toolkit or install off PyPI? I have two functions that I use that are basically obj.__name__ and type(obj).__name__ that I just import or copy-paste whenever I’m writing a lot of classes that need a repr, which seems to be exactly your use case, and I’ve never been bothered by doing that, much less considered that maybe it’s worth having either one as a builtin, before now. _______________________________________________ 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/HGSFWSUNM2BAVTXJRB3GMOUS2IQMHEVL/ Code of Conduct: http://python.org/psf/codeofconduct/