Why would an object always be linked to a variable name, and why only one name?
Le mar. 12 sept. 2023 à 10:23, Dom Grigonis <dom.grigo...@gmail.com> a écrit : > As far as I understand, it is not possible. Is it? > > Something similar to: > > var = 710 > variable_name = [k for k, v in locals().items() if v == 710][0] > print("Your variable name is " + variable_name) > > ,except robust. > > Possible ways to expose it: > * builtin function `varname(obj: object) —> str` > * object.__varname__ dunder (this one wouldn’t clutter general namespace) > > I am working on some code and just got to the point where it seems I could > make use of it. The case is as follows: > > # What I do now:class A: > defaults = dict() > > def set_default(self, a): > self.defaults['a'] = a > > def make_something(self, a=None): > a = a if a is not None else self.defaults.get('a') > return Something(a) > # What I would like to be able to do:class A: > defaults = dict() > > def set_default(self, a): > self.defaults[a.__varname__] = a > > def make_something(self, a=None): > a = a if a is not None else self.defaults.get(a.__varname__) > return Something(a) > > > In this case I like second one, because it allows a tight coupling of > variable names, which has the following benefits: > 1. General simplification, where one doesn’t have to think variable name > and its key value in dictionary. Code looks cleaner. > 2. If one was to change a variable name of `set_default` it would > immediately surface as an error. > 3. For someone working with IDEs or making use of clever multiple > selection tools, it would be easy to change all in one go. > > Any reasons why the above would not be a good practice? > Any reasons why exposing it is not a good idea? > Would this be difficult to achieve from python dev’s perspective? > > > — This one can’t be solved with deferred eval :/ — > Regards, > DG > _______________________________________________ > 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/H3O6N2W62EDU75JEQQGN63HETAZNANLP/ > Code of Conduct: http://python.org/psf/codeofconduct/ > -- Antoine Rozo
_______________________________________________ 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/RINOBZMXRJIHY2U7AYKKA5YAXZ5WJNAP/ Code of Conduct: http://python.org/psf/codeofconduct/