Noob Q: subclassing or wrapping file class

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Thu Sep 17 00:09:59 CEST 2009


On Wed, 16 Sep 2009 21:56:09 +0000, kj wrote:

...
> I thought at first that I could achieve this by overriding __getattr__:
> 
>     def __getattr__(self, attribute):
>         return self.fh.__getattr__(attribute)
> 
> But to my surprise this did not work too well.  For example, if I use a
> GzipFile object as the argument to MyFile, the iterator of the resulting
> object works as expected, but if I attempt to access its closed
> attribute I get the error
> 
> AttributeError: GzipFile instance has no attribute '__getattr__'
> 
> And it doesn't have __getattribute__ either.  (And here I'd been
> thinking that __getattr__ and __getattribute__ were pretty much
> universal...  Clearly not!)
> 
> Is there a standard idiom that I'm missing for doing this sort of thing?

Instead of:

x.__getattr__('name')

write this:


getattr(x, 'name')



Also, do a search for "automatic delegation python", or just look at Alex 
Martelli's cookbook recipe:

http://code.activestate.com/recipes/52295/




-- 
Steven



More information about the Python-list mailing list