[Python-Dev] 'hasattr' is broken by design

Nick Coghlan ncoghlan at gmail.com
Mon Aug 23 23:40:32 CEST 2010


> Properties are allowed to do whatever the heck they want. That doesn't mean
> that you have to execute code to determine whether they exist or not.

If you don't want to execute properties, do the lookup on the type,
not the instance (obviously, you know the dance you need to do, since
you've linked the code where you did it). Having apparently simple
query operations like hasattr/getattr/len/etc execute arbitrary code
is where much of the language's flexibility comes from, so I don't see
how it can really be surprising when it happens.

To me, Python's definition of an object having an attribute is "Object
x has an attribute y if x.y does not raise AttributeError". That means
it can't figure out whether or not the attribute exists without
actually attempting to retrieve it. There are a few places where we
instead use a heuristic that says an attribute *probably* exists if it
appears in the instance dictionary, or in the dictionary of one of the
types in the MRO, and magic methods have the rule that they must be
defined on the type rather than the instance in order to count from
the interpreter's point of view, but neither of those things change
the basic definition.

For the record, +1 on narrowing the scope of the exception suppression
in hasattr() to only AttributeError, and adding new C API functions
that expose the new behaviour. (I've actually long assumed that
AttributeError *was* the only thing suppressed by hasattr()).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-Dev mailing list