`Invalid` exception, `html_quote ` and unicode

rabio-h7QdYz1kt/[email protected] <rabio-h7QdYz1kt/[email protected]> Tue, 07 Oct 2008 17:11:20 +0200
Newsgroups gmane.comp.python.formencode
Message-ID <[email protected]>
Hi,

I have problems with setting ``errors`` in ``htmlfill.render()`` as
dictionary with values as ``Invalid`` exception instances with
unicode ``msg``. I get ``UnicodeEncodeError`` from
``html_quote()``. Problem exist in version 1.0.1 and in current code from svn.

When looked in code from svn I found that some attempt was made to
handle unicode in ``html_quote()`` by using ``__unicode__()`` method
if object passed to it provide one. Unfortunately ``class`` Invalid
haven't.

Adding this to ``Invalid`` class definition work for me::

    def __unicode__(self):                                   
        val = self.msg
        if isinstance(val, unicode):
            return val
        else:
            return unicode(val)

Probably ``__str__()`` method should be change also to always return
``str`` type object because now if ``msg`` is unicode--unicode will be
returned and that is not what is probably expected.

One thing need additional consideration--in solution shown above only
default encoding (ascii) is used. Some users may need to customize
this. Additional key parameter ``encoding`` that could be passed to
``Invalid.__init__()`` could handle this. It then should be used in
``__str__()`` and ``__unicode__()``. E.g. like this::

    def __unicode__(self):                                   
        val = self.msg
        if isinstance(val, unicode):
            return val
        elif encoding:
            return unicode(val, encoding)
        else:
            return unicode(val)


- Krzysiek


-------------------------------------------------------------------------
This SF.Net email is sponsored by the Moblin Your Move Developer's challenge
Build the coolest Linux based applications with Moblin SDK & win great prizes
Grand prize is a trip for two to an Open Source event anywhere in the world
http://moblin-contest.org/redirect.php?banner_id=100&url=/