I believe Python 3.8's '=' f-string specifier (
https://docs.python.org/3/whatsnew/3.8.html#f-strings-support-for-self-docum...)
combined with __name__ does what you'd want:
return f'{self.__class__.__name__}({self.name=}, {self.age=})'
Outside of the __name__ dance, this is a bit more concise (and IMO
readable) than C#'s nameof.
On that note, for simple classes like this, namedtuples or 3.7's
dataclasses would serve the purpose a bit more nicely.
On Tue, Jan 21, 2020, 12:51 PM Johan Vergeer
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/... ). 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 do you think about this? _______________________________________________ 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/UUFFAI... Code of Conduct: http://python.org/psf/codeofconduct/