473,832 Members | 2,196 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PEP263 + exec statement

Hello all,

I have a module that retrieves code snippets from a database to be
executed on the fly [1]. As I make heavy use of accented characters
inside strings (I'm in Brazil), it came to my attention that the exec
statement does not implement PEP 263 encoding checking. It does not
issue any warning when fed with arbitrary code that includes non-ASCII
characters. I am not sure if this is:

1) a design feature;
2) a bug on PEP 263 implementation;
3) a side effect of the fact that exec is not recommended anyway, and
that it will probably be deprecated at some point.

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.

----
[1] yes, I know about the security concerns regarding exec, but that
was the best design choice for several other reasons.

--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmai l.com
mail: ca********@yaho o.com
Jul 18 '05 #1
5 1543
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_st r); 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 :)

Cheers,
Nick.
Jul 18 '05 #2
On Fri, 26 Nov 2004 23:56:47 +1000, Nick Coghlan <nc******@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_st r); 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: ca********@gmai l.com
mail: ca********@yaho o.com
Jul 18 '05 #3
Carlos Ribeiro wrote:
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')
...: """


Even with a source encoding declared, I believe this statement still creates an
ASCII string, so the encoding information gets lost. What happens if you make it
explicitly unicode? (i.e. s = u"""". . . etc)

The way I read the PEP, compile() always treats string objects as ASCII, and
only deals with encodings for unicode objects.

My results below at least show that whether the string object is str or unicode
makes a difference, whereas exec vs compile() does not. ('u' in the following
code is the same as your 's', but unicode instead an ASCII string).

My system is well and truly set up for ASCII though, so I don't think too much
more can be read into my results (I also don't know what your expected output is!).
exec s a: Ol√°!
repr(a): 'Ol\xa0!'
b: Ol
b(latin-1): Ol√°
exec u a: Ol‚Ēú√*!
repr(a): 'Ol\xc3\xa1!'
b: Ol√°
b(latin-1): Olß
exec compile(s, '<string>', 'exec') a: Ol√°!
repr(a): 'Ol\xa0!'
b: Ol
b(latin-1): Ol√°
exec compile(u, '<string>', 'exec')

a: Ol‚Ēú√*!
repr(a): 'Ol\xc3\xa1!'
b: Ol√°
b(latin-1): Olß

Cheers,
Nick.

--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #4
On Sat, 27 Nov 2004 03:02:12 +1000, Nick Coghlan <nc******@iinet .net.au> wrote:
Even with a source encoding declared, I believe this statement still creates an
ASCII string, so the encoding information gets lost. What happens if you make it
explicitly unicode? (i.e. s = u"""". . . etc)


Well, that was an quite obvious mistake of mine. But even so... when a
file is read, it's supposed to be ASCII-only, but it still gives the
warning for extended ASCII characters.

Anyway, I decided to give it a try. I'm still not sure if these are
the expected results. u is a unicode string (the same as for the
previous ASCII test). e is the same source code, but with encoding
enabled on the second line. I

In [9]: u = u"""
...: 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 [10]: e = u"""
....: # -*- coding: iso-8859-1 -*-
....: a = "OlŠ!"
....: print "a:", a
....: print "repr(a):", repr(a)
....: b = u"OlŠ"
....: print "b:", b
....: """

In [11]: exec u
a: Ol√°!
repr(a): 'Ol\xc3\xa1!'
b: OlŠ
b(latin-1): OlŠ

In [12]: exec e
a: Ol√°!
repr(a): 'Ol\xc3\xa1!'
b: OlŠ

In [13]:

Curious as I am, I decided to do some tests. I found something quite
weird when I added I tried to concatenate the comment on the string.
Exec failed with a weird message, but worked after encoding.

In [64]: u
Out[64]: u'\na = "Ol\xe1!"\nprin t "a:", a\nprint "repr(a):",
repr(a)\nb = u"Ol\xe1"\nprin t "b:", b\nprint "b(latin-1):",
b.encode(\'lati n-1\')\n'

In [65]: e = "# -*- coding: iso-8859-1 -*-\n" + u

In [66]: exec e
---------------------------------------------------------------------------
SystemError Traceback (most recent call last)

/home/cribeiro/work/CherryPy/branches/cribeiro-experimental/<console>

SystemError: compile_node: unexpected node type

In [67]: e = u"# -*- coding: iso-8859-1 -*-\n" + u

In [68]: exec e
---------------------------------------------------------------------------
SystemError Traceback (most recent call last)

/home/cribeiro/work/CherryPy/branches/cribeiro-experimental/<console>

SystemError: compile_node: unexpected node type

In [69]: exec e.encode('latin-1')
a: OlŠ!
repr(a): 'Ol\xe1!'
b: OlŠ
b(latin-1): OlŠ

Quite weird. Is it appropriate to post it at python-dev?

--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmai l.com
mail: ca********@yaho o.com
Jul 18 '05 #5
Carlos Ribeiro wrote:
It does not
issue any warning when fed with arbitrary code that includes non-ASCII
characters. I am not sure if this is:

1) a design feature;
2) a bug on PEP 263 implementation;
3) a side effect of the fact that exec is not recommended anyway, and
that it will probably be deprecated at some point.


It is rather

4) almost out of scope of PEP 263, which, in its first sentence,
restricts itself to Python source *files*

There are a few places where Python source code is not stored
in files, namely:
- exec
- eval
- compile
- interactive mode
- IDLE shell

The PEP isn't really precise on what to do in these cases, it certainly
isn't fair to require an encoding declaration in all of them. In
particular, for interactive mode, it is undesirable to require such a
declaration. It is also unnecessary, since, in interactive mode, you
almost certainly know the encoding from sys.stdin.encod ing.

So Python 2.4 will use sys.stdin.encod ing for code entered in
interactive mode. My plan is that compile() grows an argument
to specify the encoding of the string, falling back to ASCII
if none is specified. Then, exec and eval would not need to
be modified - people who want to specify an encoding outside
of the source itself could pass a code object to exec or eval,
instead of directly passing the string to these constructs.
This would also take care of IDLE, which internally uses
compile().

I have implemented these changes, but I was a little bit too
late to submit them for Python 2.4.

Regards,
Martin
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
5784
by: Toby Donaldson | last post by:
Hi all, I'm designing an educational application that will run Python code and check the output against a pre-define answer. I want to use the "exec" statement to run the code, but I don't know how to get output from it. For instance, exec works like this: >>> code = """ for i in xrange(1, 5):
4
2194
by: Roman Suzi | last post by:
hi! One of my old web projects uses execfile alot, because its data are stored in Python. How do I suppress all those warnings DeprecationWarning: Non-ASCII character '\xd2' in file ffff.py on line 5, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details in one place (preferably at execfile() call)?
2
4190
by: tedsuzman | last post by:
----- def f(): ret = 2 exec "ret += 10" return ret print f() ----- The above prints '12', as expected. However,
1
2238
by: Andr? Roberge | last post by:
I have the following two files: #--testexec.py-- def exec_code(co): try: exec co except: print "error" #-- test.py--
45
2695
by: It's me | last post by:
I am new to the Python language. How do I do something like this: I know that a = 3 y = "a" print eval(y)
0
10230
by: Jan | last post by:
I store sql-commands in a database table. In the first step I get the sql command out of the database table with embedded sql. In the second step I try to execute the command, which i got from the database table, using dynamic sql. Executing 'EXEC SQL DESCRIBE SELECT LIST FOR S INTO select_dp;' the error code -2149 is returned That means "Specified partition does not exist". Does anybody know if it is a database problem or a problem of
8
3327
by: R. Bernstein | last post by:
In doing the extension to the python debugger which I have here: http://sourceforge.net/project/showfiles.php?group_id=61395&package_id=175827 I came across one little thing that it would be nice to get done better. I notice on stack traces and tracebacks, an exec or execfile command appears as a stack entry -- probably as it should since it creates a new environment. However the frame information for exec or execfile looks like this:...
5
2441
by: TPJ | last post by:
I have the following code: ----------------------------------- def f(): def g(): a = 'a' # marked line 1 exec 'a = "b"' in globals(), locals() print "g: a =", a
4
2377
by: Michael | last post by:
Hi, I'm having difficulty finding any previous discussion on this -- I keep finding people either having problems calling os.exec(lepev), or with using python's exec statement. Neither of which I mean here. Just for a moment, let's just take one definition for one of the
0
9795
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9642
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10540
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10212
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9319
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectóplanning, coding, testing, and deploymentówithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7753
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Duprť who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5789
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4421
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.