hasattr + __getattr__: I think this is Python bug

Duncan Booth duncan.booth at invalid.invalid
Tue Jul 20 11:52:52 EDT 2010


dmitrey <dmitrey.kroshko at scipy.org> wrote:

>> e.g. one that just looks in the object's dictionary so as to avoid
>> returning true for properties or other such fancy attributes. 
> 
> So can anyone explain me how to look into object's dict? As I have
> wrote, "something in dir(...)" requires O(numOfFields) while I would
> like to use o(log(n))

O(1) might be even better. Try this:

def dmitry_hasattr(obj, name):
	"""Checks for existence of an attribute directly in an
	object's dictionary. Doesn't see all attributes but doesn't
	have side effects."""
	d = getattr(obj, '__dict__')
	if d is not None:
		return name in d
	return False


-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list