[Tutor] use of __new__

spir denis.spir at gmail.com
Thu Mar 11 20:03:35 CET 2010


Hello,

I need a custom unicode subtype (with additional methods). This will not be directly used by the user, instead it is just for internal purpose.
I would like the type to be able to cope with either a byte str or a unicode str as argument. In the first case, it needs to be first decoded. I cannot do it in __init__ because unicode will first try to decode it as ascii, which fails in the general case. So, I must have my own __new__.
The issue is the object (self) is then a unicode one instead of my own type.

class Unicode(unicode):
    Unicode.FORMAT = "utf8"
    def __new__(self, text, format=None):
        # text can be str or unicode
        format = Unicode.FORMAT if format is None else format
        if isinstance(text,str):
            text = text.decode(format)
        return text
    .......

x = Unicode("abc")	# --> unicode, not Unicode

Denis
________________________________

la vita e estrany

spir.wikidot.com



More information about the Tutor mailing list