On Monday, November 30, 2015 at 8:01:14 PM UTC-5, Steven D'Aprano wrote: > I'm trying to understand why vars() exists. Does anyone use it? > > Every time I try to use it, I find it doesn't quite do what I want. And even > if it did, there are more obvious and/or correct alternatives. > > For instance, I want to check whether a particular name is an instance > attribute. So first I write: > > "name" in obj.__dict__ > > but when I see the dunder name I think that's an implementation detail. And > sure enough, not all instances have a __dict__ (e.g. if it uses __slots__ > instead) and so I re-write it as: > > "name" in vars(obj) > > but that also fails if obj has no instance __dict__. > > But why am I looking just in the instance __dict__? Chances are I should be > looking for the attribute *anywhere* in the instance/class/superclass > hierarchy: > > hasattr(obj, "name") > > Or, if you are worried about triggering dynamic attributes using > __getattr__, you can do this: > > sentinel = object() > inspect.getattr_static(obj, "name", sentinel) is not sentinel > > which only checks for pre-existing attributes without triggering > __getattr__, __getattribute__, or the descriptor protocol. > > > Either way, vars() doesn't solve the problem. What problem does it solve?
I'm using dir and vars pretty often when I'm trying to figure out new code or review a pull request, or when I'm reviewing code that I don't remember. Both are convenient for quickly checking which attributes are available at the moment. I never realized that there might be issues with "fancy" problems. `vars` is convenient, for example, to check which attributes have been initialized to None, and which already have assigned values. And checking again after some calculations, I roughly see which attributes have been added or changed in the mean time. aside: I'm boring and like code that has no magic, especially if I have to maintain it. Josef > > > > -- > Steven -- https://mail.python.org/mailman/listinfo/python-list