Is vars() the most useless Python built-in ever?
Steven D'Aprano
steve at pearwood.info
Mon Nov 30 20:00:46 EST 2015
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?
--
Steven
More information about the Python-list
mailing list