durusmail: qp: Subclassing u8, h8
Subclassing u8, h8
2007-09-17
Re: Subclassing u8, h8
2007-09-17
2007-09-18
2007-09-18
Subclassing u8, h8
Michael Watkins
2007-09-17
On the weekend I decided to build a simple file template system entirely
dependent on QPY - essentially u8 or h8 strings loaded from persistent files,
with some additional capabilities.

I'd started out with my u8 or h8 template instance as an attribute of a
Template class. Works well, but I decided I wanted to expose more methods of
u8/h8, enough to make me want to subclass u8. I ran into problems with certain
methods of u8/h8 (the binary methods):

First, regular u8/h8 operations:

    ->> u8
    
    ->> t = u8('%(name)s')
    ->> t
    u'%(name)s'
    ->> t % dict(name='Sally')
    u'Sally'
    ->> t + t
    u'%(name)s%(name)s'

And then a simple subclass. Would someone be so kind as to explain why
subclassing u8 fails in this:

    />> class Template(h8):
    |..     pass
    \__
    ->> Template
    
    ->> template = Template('%(name)s')
    ->> template
    u'%(name)s'
    ->> template % dict(name='Sally')
    Traceback (most recent call last):
      File "", line 2, in 
    TypeError: unsupported operand type(s) for %: 'Template' and 'dict'

I've tried various approaches including overriding __new__ and haven't managed
to push forward. My guess (WAG that is) is that its the C implementation of u8
or unicode.

Ah, looking deeper at u8 I see the C implementation appears to be causing this
- the instance of the u8 subclass I'm guessing doesn't meet the strict
definition of is_u8_object / is_h8_object and thus NotImplemented is returned,
which I believe Python's abstract.c returns as the unsupported operand
TypeError.

For now I'll just override the binary operations (and any others that creep up
in testing).

Whether or not what I'm doing proves useful in the end is yet to be seen...
Mike

reply