hasattr(obj, attr) overloading?

Eric Jacobs x at x.x
Mon Nov 1 02:55:09 CET 1999

claudius at catlover.com wrote:
> Is there a way to overload the hasattr method (by default it calls __getattr__
> and checks for an exception.  However, my __getattr__ can be a heavy hit that
> I'd rather avoid for hasattr calls.)
> If not, perhaps a feature for the next minor revision?

How 'bout:

def hasattr(o, a, orig_hasattr=hasattr):
	if orig_hasattr(o, "__hasattr__"):
		return o.__hasattr__(a)
	return orig_hasattr(o, a)

__builtins__.hasattr = hasattr

This is assuming, of course, that the "heavy hit" won't occur checking for
a __hasattr__ attribute. It also won't work for a C module that wants to
call PyObject_HasAttr[String]. Finally, you'd have to mess around with it
a little bit if you want to check for attributes of a class (the class
will return an unbound method.)

The default argument avoids losing the original reference to the built-in
hasattr. Assigning to the __builtins__ module will allow other (Python)
modules to use the new function.

More information about the Python-list mailing list