Noob Q: subclassing or wrapping file class

Steven D'Aprano steven at
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:


write this:

getattr(x, 'name')

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


More information about the Python-list mailing list