I have a library that accepts a file-like object but assumes that it has a valid .name unless that name is None. This causes it to break when I pass e.g. someproc.stdout as it has a name of <fdopen>. Unfortunately the attribute cannot be deleted or overwritten.
So I've written this simple wrapper to return None in case the name attribute is requested.
class InterceptAttrWrapper(object):
def __init__(self, obj, attr, value):
self.obj = obj
self.attr = attr
self.value = value
def __getattribute__(self, name):
ga = lambda attr: object.__getattribute__(self, attr)
if name == ga('attr'):
return ga('value')
return getattr(ga('obj'), name)
This seems to work fine, I'm using it like this:
proc = subprocess.Popen(..., stdout=subprocess.PIPE)
some_func(InterceptAttrWrapper(proc.stdout, 'name', None))
However, I wonder if:
- My
InterceptAttrWrapperobject is missing something that could cause problems. - There is a better way to access attributes within
__getattribute__. That lambda I'm using right now looks pretty ugly.