PEP263 + exec statement

Carlos Ribeiro carribeiro at gmail.com
Fri Nov 26 11:13:05 EST 2004


On Fri, 26 Nov 2004 23:56:47 +1000, Nick Coghlan <ncoghlan at email.com> wrote:
> Carlos Ribeiro wrote:
> > Does anyone have more information on this? I have tried Google in
> > vain. It seems that exec is not that popular (which is a good sign,
> > IMHO), and that nobody else had this problem before.
> 
> Does compile() work? (i.e. "bytecode = compile(code_str); exec bytecode" instead
> of "exec code_str").
> 
> PEP 263 states explicitly that feeding a unicode string to compile() should
> respect the encoding. It's silence on the question of exec fails to inspire
> confidence. . .
> 
> If compile() does work even though exec doesn't, it would explain why exec has
> never been fixed :)

In [3]: s = """
   ...: a = "Olá!"
   ...: print "a:", a
   ...: print "repr(a):", repr(a)
   ...: b = u"Olá"
   ...: print "b:", b
   ...: print "b(latin-1):", b.encode('latin-1')
   ...: """

In [4]: exec s
a: Olá!
repr(a): 'Ol\xe1!'
b: Olá
b(latin-1): Olá

In [5]: c = compile(s, '<string>', 'exec')

In [6]: print c
<code object ? at 0x403c8660, file "<string>", line 2>

In [7]: exec c
a: Olá!
repr(a): 'Ol\xe1!'
b: Olá
b(latin-1): Olá

No exceptions at any point with Python 2.3, which I thought would
support the encoding PEP (as it does for source files -- it issues a
warning). I haven't tested it with 2.4 -- don't have it installed
here, so I don't know what is it supposed to do.

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list