python 3, subclassing TextIOWrapper.

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Mar 22 15:33:14 EDT 2009


En Sun, 22 Mar 2009 15:11:37 -0300, R. David Murray  
<rdmurray at bitdance.com> escribió:
> "Gabriel Genellina" <gagsl-py2 at yahoo.com.ar> wrote:
>> En Sat, 21 Mar 2009 23:58:07 -0300, <lambertdw at corning.com> escribió:
>> >
>> > class file(io.TextIOWrapper):
>> >
>> >     '''
>> >         Enhance TextIO.  Streams have many sources,
>> >         a file name is insufficient.
>> >     '''
>> >
>> >     def __init__(self,stream):
>> >         #self.stream = stream
>> >         super().__init__(stream.buffer)
>> >
>> >
>> > print(file(open('p.py')).read())
>>
>>
>> [...] So, if you're not interested in the TextIOWrapper object, don't  
>> create it in the first place. That means, don't use the open() shortcut  
>> and build
>> the required pieces yourself.
>>
> I'm wondering if what we really need here is either some way to tell open
> to use a specified subclass(s) instead of the default ones, or perhaps
> an 'open factory' function that would yield such an open function that
> otherwise is identical to the default open.
>
> What's the standard python idiom for when consumer code should be
> able to specialize the classes used to create objects returned from
> a called package?  (I'm tempted to say monkey patching the module,
> but that can't be optimal :)

I've seen:
- pass the desired subclass as an argument to the class constructor /  
factory function.
- set the desired subclass as an instance attribute of the factory object.
- replacing the f_globals attribute of the factory function (I wouldn't  
recomend this! but sometimes is the only way)

In the case of builtin open(), I'm not convinced it would be a good idea  
to allow subclassing. But I have no rational arguments - just don't like  
the idea :(

-- 
Gabriel Genellina




More information about the Python-list mailing list