Python print isn't using __repr__
, __unicode__
or __str__
for my unicode subclass when printing. Any clues as to what I am doing wrong?
Here is my code:
Using Python 2.5.2 (r252:60911, Oct 13 2009, 14:11:59)
>>> class MyUni(unicode):
... def __repr__(self):
... return "__repr__"
... def __unicode__(self):
... return unicode("__unicode__")
... def __str__(self):
... return str("__str__")
...
>>> s = MyUni("HI")
>>> s
'__repr__'
>>> print s
'HI'
I'm not sure if this is an accurate approximation of the above, but just for comparison:
>>> class MyUni(object):
... def __new__(cls, s):
... return super(MyUni, cls).__new__(cls)
... def __repr__(self):
... return "__repr__"
... def __unicode__(self):
... return unicode("__unicode__")
... def __str__(self):
... return str("__str__")
...
>>> s = MyUni("HI")
>>> s
'__repr__'
>>> print s
'__str__'
[EDITED...] It sounds like the best way to get a string object that isinstance(instance, basestring) and offers control over unicode return values, and with a unicode repr is...
>>> class UserUnicode(str):
... def __repr__(self):
... return "u'%s'" % super(UserUnicode, self).__str__()
... def __str__(self):
... return super(UserUnicode, self).__str__()
... def __unicode__(self):
... return unicode(super(UserUnicode, self).__str__())
...
>>> s = UserUnicode("HI")
>>> s
u'HI'
>>> print s
'HI'
>>> len(s)
2
The _str_ and _repr_ above add nothing to this example but the idea is to show a pattern explicitly, to be extended as needed.
Just to prove that this pattern grants control:
>>> class UserUnicode(str):
... def __repr__(self):
... return "u'%s'" % "__repr__"
... def __str__(self):
... return "__str__"
... def __unicode__(self):
... return unicode("__unicode__")
...
>>> s = UserUnicode("HI")
>>> s
u'__repr__'
>>> print s
'__str__'
Thoughts?