[Python-Dev] 'hasattr' is broken by design (original) (raw)

Nick Coghlan ncoghlan at gmail.com
Tue Aug 24 00:25:03 CEST 2010


On Tue, Aug 24, 2010 at 8:15 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:

Now, it may be worth considering an addition to the inspect module that was basically:

def getattrstatic(obj, attr):  """Retrieve attributes without triggering dynamic lookup via the descriptor protocol,  getattr or getattribute.  Note: this function may not be able to retrieve all attributes reported by dir(obj)  """  try:  instancedict = object.getattribute(obj, "dict")  except AttributeError:  pass  else:  if attr in instancedict:  return instancedict[attr]  for entry in getmro(obj.class):  try:  return entry.dict[attr]  except AttributeError:  pass

Second attempt with a default value parameter and correctly raising AttributeError if not found:

_sentinel = object() def getattr_static(obj, attr, default=_sentinel): """Retrieve attributes without triggering dynamic lookup via the descriptor protocol, getattr or getattribute.

    Note: this function may not be able to retrieve all attributes
    reported by dir(obj)
"""
try:
    instance_dict = object.__getattribute__(obj, "__dict__")
except AttributeError:
    pass
else:
    if attr in instance_dict:
        return instance_dict[attr]
for entry in getmro(obj.__class__):
    try:
        return entry.__dict__[attr]
    except AttributeError:
        pass
if default is not _sentinel:
    return default
raise AttributeError(attr)

Cheers, Nick.

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



More information about the Python-Dev mailing list