Vaibhav Bajpai
Vaibhav Bajpai

Reputation: 16814

no UnicodeError when using print with a default encoding set to ASCII

After reading: Dive into Python: Unicode Discussion

I got curious to try printing my name in the indic script. I am using v2.7.2 -

>>> import sys
>>> sys.getdefaultencoding()
'ascii'
>>> name = u'\u0935\u0948\u092D\u0935'
>>> print name
वैभव

I was expecting print name to give me UnicodeError since the defaultencoding is set to ASCII so the auto-coercion to ASCII from Unicode shouldn't work.

What am I missing?

Upvotes: 5

Views: 158

Answers (1)

unutbu
unutbu

Reputation: 880927

print uses sys.stdout.encoding, not sys.getdefaultencoding():

When Python finds its output attached to a terminal, it sets the sys.stdout.encoding attribute to the terminal's encoding. The print statement's handler will automatically encode unicode arguments into str output.

>>> import sys
>>> print(sys.stdout.encoding)
utf-8
>>> print(sys.getdefaultencoding())
ascii
>>> name = u'\u0935\u0948\u092D\u0935'
>>> print name
वैभव

Upvotes: 9

Related Questions