unicode question

wolfgang haefelinger wh2005 at web.de
Sun Nov 21 06:09:30 EST 2004


Hi Experts,

I'm actually not a Python expert so please bear with me and my naive
questions and remarks:

I was actually thinking that

 print x

is just kind of shortcur for writing (simplifying bit):

 import sys
 if not (isinstance(x,str) or isinstance(x,unicode)) and x.__str__ :
    x = x.__str__()
 sys.stdout.write(x)

Or in words: if x is not a string type but has method __str__ then

 print x

behaves like

 print x.__str__()

Given this assumption I'm wondering then why  print x.__str__()
works but print x does not?

Is this a bug??

Cheers,
Wolfgang.



""Martin v. Löwis"" <martin at v.loewis.de> wrote in message 
news:41A061E1.8050203 at v.loewis.de...
> Kent Johnson wrote:
>> Martin v. Löwis wrote:
>>
>>> wolfgang haefelinger wrote:
>>>
>>>> I wonder especially about case 2. I can see that "print y" makes a call 
>>>> to
>>>> Y.__str__() . But Y.__str__() can be printed?? So what is 'print' 
>>>> exactly doing?
>>>
>>>
>>>
>>> It looks at sys.stdout.encoding. If this is set, and the thing to print
>>> is a unicode string, it converts it to the stream encoding, and prints
>>> the result of the conversion.
>>
>>
>> I hate to contradict an expert, but ISTM that it is 
>> sys.getdefaultencoding() ('ascii') that is the problem, not 
>> sys.stdout.encoding ('cp437')
>
> It seems we were answering different parts of the question. I answered
> the part "What is 'print' exactly doing"; you answered the part as to
> what the problem with str() conversion is (although I'm not sure whether
> the OP has actually asked that question).
>
> Also, the one case that is interesting here was not in your experiment:
> try
>
> print gamma
>
> This should work, regardless of sys.getdefaultencoding(), as long as
> sys.stdout.encoding supports the characters to be printed.
>
> Regards,
> Martin 





More information about the Python-list mailing list