On 24/08/2010 01:25, Nick Coghlan wrote:
On Tue, Aug 24, 2010 at 8:15 AM, Nick Coghlan<ncogh...@gmail.com>  wrote:
Now, it may be worth considering an addition to the inspect module
that was basically:

def getattr_static(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:
        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
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)


This doesn't correctly handle the case where obj is a type object or obj uses __slots__.

If I have time (currently on vacation with only intermittent internet access) I'll provide an update.

Michael


Cheers,
Nick.



--
http://www.ironpythoninaction.com/

_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to