Code

Ticket #1664: unicode.py

File unicode.py, 1.3 KB (added by Noah Slater, 8 years ago)

A set of classes and tests for lazy Unicode evaluation

Line 
1#!/usr/bin/env python
2
3class UnicodeContainer:
4
5    def __init__(self, unicode):
6        self._unicode = unicode
7
8    def __str__(self):
9        raise TypeError("string coercion on non bytestream")
10
11    def __unicode__(self):
12        return self._unicode
13
14class LazyUnicodeContainer(UnicodeContainer):
15    def __init__(self, function, *args, **kwargs):
16        self._function = function
17        self._args = args
18        self._kwargs = kwargs
19
20    def __unicode__(self):
21        if not hasattr(self, '_unicode'):
22            self._unicode = self._function(*self._args, **self._kwargs)
23        return self._unicode
24
25class LazyUnicodeDispatcher:
26
27    def __init__(self, function):
28        self._function = function
29
30    def __call__(self, *args, **kwargs):
31        return LazyUnicodeContainer(self._function, *args, **kwargs)
32
33def test_function(message):
34    print "Calling ugettext"
35    return message.decode('utf-8')
36
37print "Setting up the LazyUnicodeDispatcher"
38lazy_unicode_dispatcher = LazyUnicodeDispatcher(test_function)
39
40print "Calling the LazyUnicodeDispatcher"
41lazy_unicode_container = lazy_unicode_dispatcher('\xc2\xbfQu\xc3\xa9 pasa?')
42
43print "Converting the LazyUnicodeContainer"
44unicode_value = unicode(lazy_unicode_container)
45
46print "Printing results:"
47print "    %s" % type(unicode_value)
48print "    %s" % unicode_value