Noob Q: subclassing or wrapping file class

kj at
Thu Sep 17 01:06:18 CEST 2009

In <pan.2009. at> Steven D'Aprano <steven at> writes:

>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')

This did the trick.

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


That was instructive.  Thanks!


More information about the Python-list mailing list