Patch #1550800: make exec a function.

This commit is contained in:
Georg Brandl 2006-09-06 06:51:57 +00:00
parent 4e472e05bd
commit 7cae87ca7b
105 changed files with 1246 additions and 1583 deletions

View file

@ -164,7 +164,7 @@ def _test():
else:
print "accessible"
\n"""
exec testcode
exec(testcode)
print '='*20, "Using rexec:", '='*20
import rexec
r = rexec.RExec()

View file

@ -362,7 +362,7 @@ class Bdb:
cmd = cmd+'\n'
try:
try:
exec cmd in globals, locals
exec(cmd, globals, locals)
except BdbQuit:
pass
finally:

View file

@ -72,7 +72,7 @@ import sys, os
if sys.version >= '2.3':
import UserDict
from weakref import ref
exec """
exec("""
class _iter_mixin(UserDict.DictMixin):
def _make_iter_cursor(self):
cur = _DeadlockWrap(self.db.cursor)
@ -145,7 +145,7 @@ class _iter_mixin(UserDict.DictMixin):
except _bsddb.DBCursorClosedError:
# the database was modified during iteration. abort.
return
"""
""")
else:
class _iter_mixin: pass

View file

@ -137,7 +137,7 @@ class Profile(_lsprof.Profiler):
def runctx(self, cmd, globals, locals):
self.enable()
try:
exec cmd in globals, locals
exec(cmd, globals, locals)
finally:
self.disable()
return self

View file

@ -910,7 +910,7 @@ def test(environ=os.environ):
print_environ(environ)
print_environ_usage()
def f():
exec "testing print_exception() -- <I>italics?</I>"
exec("testing print_exception() -- <I>italics?</I>")
def g(f=f):
f()
print "<H3>What follows is a test, not an actual exception:</H3>"

View file

@ -100,7 +100,7 @@ class InteractiveInterpreter:
"""
try:
exec code in self.locals
exec(code, self.locals)
except SystemExit:
raise
except:

View file

@ -440,32 +440,6 @@ class Ellipsis(Node):
def __repr__(self):
return "Ellipsis()"
class Exec(Node):
def __init__(self, expr, locals, globals, lineno=None):
self.expr = expr
self.locals = locals
self.globals = globals
self.lineno = lineno
def getChildren(self):
children = []
children.append(self.expr)
children.append(self.locals)
children.append(self.globals)
return tuple(children)
def getChildNodes(self):
nodelist = []
nodelist.append(self.expr)
if self.locals is not None:
nodelist.append(self.locals)
if self.globals is not None:
nodelist.append(self.globals)
return tuple(nodelist)
def __repr__(self):
return "Exec(%s, %s, %s)" % (repr(self.expr), repr(self.locals), repr(self.globals))
class FloorDiv(Node):
def __init__(self, (left, right), lineno=None):
self.left = left

View file

@ -762,7 +762,6 @@ class StackDepthTracker:
'PRINT_ITEM': -1,
'RETURN_VALUE': -1,
'YIELD_VALUE': -1,
'EXEC_STMT': -3,
'BUILD_CLASS': -2,
'STORE_NAME': -1,
'STORE_ATTR': -2,

View file

@ -1043,18 +1043,6 @@ class CodeGenerator:
self.emit('ROT_THREE')
self.emit('STORE_SUBSCR')
def visitExec(self, node):
self.visit(node.expr)
if node.locals is None:
self.emit('LOAD_CONST', None)
else:
self.visit(node.locals)
if node.globals is None:
self.emit('DUP_TOP')
else:
self.visit(node.globals)
self.emit('EXEC_STMT')
def visitCallFunc(self, node):
pos = 0
kw = 0

View file

@ -468,20 +468,6 @@ class Transformer:
names.append(nodelist[i][1])
return Global(names, lineno=nodelist[0][2])
def exec_stmt(self, nodelist):
# exec_stmt: 'exec' expr ['in' expr [',' expr]]
expr1 = self.com_node(nodelist[1])
if len(nodelist) >= 4:
expr2 = self.com_node(nodelist[3])
if len(nodelist) >= 6:
expr3 = self.com_node(nodelist[5])
else:
expr3 = None
else:
expr2 = expr3 = None
return Exec(expr1, expr2, expr3, lineno=nodelist[0][2])
def assert_stmt(self, nodelist):
# 'assert': test, [',' test]
expr1 = self.com_node(nodelist[1])
@ -1429,7 +1415,6 @@ _legal_node_types = [
symbol.raise_stmt,
symbol.import_stmt,
symbol.global_stmt,
symbol.exec_stmt,
symbol.assert_stmt,
symbol.if_stmt,
symbol.while_stmt,

View file

@ -1209,8 +1209,8 @@ class DocTestRunner:
# keyboard interrupts.)
try:
# Don't blink! This is where the user's code gets run.
exec compile(example.source, filename, "single",
compileflags, 1) in test.globs
exec(compile(example.source, filename, "single",
compileflags, 1), test.globs)
self.debugger.set_continue() # ==== Example Finished ====
exception = None
except KeyboardInterrupt:

View file

@ -82,11 +82,11 @@ try:
f = getattr(_hashlib, opensslFuncName)
f()
# Use the C function directly (very fast)
exec funcName + ' = f'
exec(funcName + ' = f')
except ValueError:
try:
# Use the builtin implementation directly (fast)
exec funcName + ' = __get_builtin_constructor(funcName)'
exec(funcName + ' = __get_builtin_constructor(funcName)')
except ValueError:
# this one has no builtin implementation, don't define it
pass

View file

@ -690,7 +690,7 @@ class ModifiedInterpreter(InteractiveInterpreter):
if self.rpcclt:
self.rpcclt.remotequeue("exec", "runcode", (code,), {})
else:
exec code in self.locals
exec(code, self.locals)
return 1
def runcode(self, code):
@ -711,7 +711,7 @@ class ModifiedInterpreter(InteractiveInterpreter):
elif debugger:
debugger.run(code, self.locals)
else:
exec code in self.locals
exec(code, self.locals)
except SystemExit:
if not self.tkconsole.closing:
if tkMessageBox.askyesno(

View file

@ -282,7 +282,7 @@ class Executive(object):
def runcode(self, code):
try:
self.usr_exc_info = None
exec code in self.locals
exec(code, self.locals)
except:
self.usr_exc_info = sys.exc_info()
if quitting:

View file

@ -323,7 +323,7 @@ class FancyModuleLoader(ModuleLoader):
m.__path__ = path
m.__file__ = filename
try:
exec code in m.__dict__
exec(code, m.__dict__)
except:
d = self.hooks.modules_dict()
if name in d:

View file

@ -301,7 +301,7 @@ class Importer:
# execute the code within the module's namespace
if not is_module:
try:
exec code in module.__dict__
exec(code, module.__dict__)
except:
if fqname in sys.modules:
del sys.modules[fqname]

View file

@ -25,7 +25,6 @@ kwlist = [
'elif',
'else',
'except',
'exec',
'finally',
'for',
'from',

View file

@ -1699,7 +1699,7 @@ class Tk(Misc, Wm):
base_tcl = os.path.join(home, '.%s.tcl' % baseName)
base_py = os.path.join(home, '.%s.py' % baseName)
dir = {'self': self}
exec 'from Tkinter import *' in dir
exec('from Tkinter import *', dir)
if os.path.isfile(class_tcl):
self.tk.call('source', class_tcl)
if os.path.isfile(class_py):

View file

@ -114,7 +114,6 @@ def_op('WITH_CLEANUP', 81)
def_op('LOAD_LOCALS', 82)
def_op('RETURN_VALUE', 83)
def_op('IMPORT_STAR', 84)
def_op('EXEC_STMT', 85)
def_op('YIELD_VALUE', 86)
def_op('POP_BLOCK', 87)
def_op('END_FINALLY', 88)

View file

@ -198,7 +198,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
globals = self.curframe.f_globals
try:
code = compile(line + '\n', '<stdin>', 'single')
exec code in globals, locals
exec(code, globals, locals)
except:
t, v = sys.exc_info()[:2]
if type(t) == type(''):

View file

@ -329,7 +329,7 @@ def _parse_object(file):
#
def create_full_form(inst, (fdata, odatalist)):
form = create_form(fdata)
exec 'inst.'+fdata.Name+' = form\n'
exec('inst.'+fdata.Name+' = form\n')
for odata in odatalist:
create_object_instance(inst, form, odata)
@ -338,7 +338,7 @@ def create_full_form(inst, (fdata, odatalist)):
# variable.
#
def merge_full_form(inst, form, (fdata, odatalist)):
exec 'inst.'+fdata.Name+' = form\n'
exec('inst.'+fdata.Name+' = form\n')
if odatalist[0].Class != FL.BOX:
raise error, 'merge_full_form() expects FL.BOX as first obj'
for odata in odatalist[1:]:
@ -374,7 +374,7 @@ def create_object_instance(inst, form, odata):
cbfunc = eval('inst.'+odata.Callback)
obj.set_call_back(cbfunc, odata.Argument)
if odata.Name:
exec 'inst.' + odata.Name + ' = obj\n'
exec('inst.' + odata.Name + ' = obj\n')
#
# Internal _create_object: Create the object and fill options
#

View file

@ -130,7 +130,7 @@ def assign_members(target, attrlist, exclist, prefix):
stmt = lhs + '=' + repr(value)
if debug: print 'exec', stmt
try:
exec stmt + '\n'
exec(stmt + '\n')
except KeyboardInterrupt: # Don't catch this!
raise KeyboardInterrupt
except:
@ -186,7 +186,7 @@ def build_subactuators(panel, super_act, al):
if name:
stmt = 'panel.' + name + ' = act'
if debug: print 'exec', stmt
exec stmt + '\n'
exec(stmt + '\n')
if is_endgroup(a):
panel.endgroup()
sub_al = getattrlist(a, 'al')
@ -236,7 +236,7 @@ def build_panel(descr):
act.addact(panel)
if name:
stmt = 'panel.' + name + ' = act'
exec stmt + '\n'
exec(stmt + '\n')
if is_endgroup(a):
panel.endgroup()
sub_al = getattrlist(a, 'al')

View file

@ -328,7 +328,7 @@ def _parse_object(file):
#
def create_full_form(inst, (fdata, odatalist)):
form = create_form(fdata)
exec 'inst.'+fdata.Name+' = form\n'
exec('inst.'+fdata.Name+' = form\n')
for odata in odatalist:
create_object_instance(inst, form, odata)
@ -337,7 +337,7 @@ def create_full_form(inst, (fdata, odatalist)):
# variable.
#
def merge_full_form(inst, form, (fdata, odatalist)):
exec 'inst.'+fdata.Name+' = form\n'
exec('inst.'+fdata.Name+' = form\n')
if odatalist[0].Class != FL.BOX:
raise error, 'merge_full_form() expects FL.BOX as first obj'
for odata in odatalist[1:]:
@ -373,7 +373,7 @@ def create_object_instance(inst, form, odata):
cbfunc = eval('inst.'+odata.Callback)
obj.set_call_back(cbfunc, odata.Argument)
if odata.Name:
exec 'inst.' + odata.Name + ' = obj\n'
exec('inst.' + odata.Name + ' = obj\n')
#
# Internal _create_object: Create the object and fill options
#

View file

@ -130,7 +130,7 @@ def assign_members(target, attrlist, exclist, prefix):
stmt = lhs + '=' + repr(value)
if debug: print 'exec', stmt
try:
exec stmt + '\n'
exec(stmt + '\n')
except KeyboardInterrupt: # Don't catch this!
raise KeyboardInterrupt
except:
@ -186,7 +186,7 @@ def build_subactuators(panel, super_act, al):
if name:
stmt = 'panel.' + name + ' = act'
if debug: print 'exec', stmt
exec stmt + '\n'
exec(stmt + '\n')
if is_endgroup(a):
panel.endgroup()
sub_al = getattrlist(a, 'al')
@ -236,7 +236,7 @@ def build_panel(descr):
act.addact(panel)
if name:
stmt = 'panel.' + name + ' = act'
exec stmt + '\n'
exec(stmt + '\n')
if is_endgroup(a):
panel.endgroup()
sub_al = getattrlist(a, 'al')

View file

@ -557,12 +557,12 @@ template = """
class %s(ComponentItem): want = '%s'
"""
exec template % ("Text", 'text')
exec template % ("Character", 'cha ')
exec template % ("Word", 'cwor')
exec template % ("Line", 'clin')
exec template % ("paragraph", 'cpar')
exec template % ("Window", 'cwin')
exec template % ("Document", 'docu')
exec template % ("File", 'file')
exec template % ("InsertionPoint", 'cins')
exec(template % ("Text", 'text'))
exec(template % ("Character", 'cha '))
exec(template % ("Word", 'cwor'))
exec(template % ("Line", 'clin'))
exec(template % ("paragraph", 'cpar'))
exec(template % ("Window", 'cwin'))
exec(template % ("Document", 'docu'))
exec(template % ("File", 'file'))
exec(template % ("InsertionPoint", 'cins'))

View file

@ -57,7 +57,7 @@ else:
# funny) and go.
#
del argvemulator, os, sys, marshal, _dir, _fp
exec __code__
exec(__code__)
else:
sys.stderr.write("%s: neither __main__.py nor __main__.pyc found\n"%sys.argv[0])
sys.exit(1)

View file

@ -588,7 +588,7 @@ class PimpPackage:
}
installTest = self._dict['Install-test'].strip() + '\n'
try:
exec installTest in namespace
exec(installTest, namespace)
except ImportError, arg:
return "no", str(arg)
except _scriptExc_NotInstalled, arg:
@ -757,7 +757,7 @@ class PimpPackage:
if line[0] == '#':
continue
if line[:6] == 'import':
exec line
exec(line)
continue
if line[-1] == '\n':
line = line[:-1]

View file

@ -459,7 +459,7 @@ class Profile:
self.set_cmd(cmd)
sys.setprofile(self.dispatcher)
try:
exec cmd in globals, locals
exec(cmd, globals, locals)
finally:
sys.setprofile(None)
return self

View file

@ -58,7 +58,7 @@ class FileDelegate(FileBase):
self.name = name
for m in FileBase.ok_file_methods + ('close',):
exec TEMPLATE % (m, m)
exec(TEMPLATE % (m, m))
class RHooks(ihooks.Hooks):
@ -310,7 +310,7 @@ class RExec(ihooks._Verbose):
"""
m = self.add_module('__main__')
exec code in m.__dict__
exec(code, m.__dict__)
def r_eval(self, code):
"""Evaluate code within a restricted environment.

View file

@ -29,7 +29,7 @@ def _run_code(code, run_globals, init_globals,
run_globals.update(__name__ = mod_name,
__file__ = mod_fname,
__loader__ = mod_loader)
exec code in run_globals
exec(code, run_globals)
return run_globals
def _run_module_code(code, init_globals=None,

View file

@ -135,7 +135,7 @@ def addpackage(sitedir, name, known_paths):
if line.startswith("#"):
continue
if line.startswith("import"):
exec line
exec(line)
continue
line = line.rstrip()
dir, dircase = makepath(sitedir, line)

View file

@ -191,7 +191,7 @@ class _socketobject(object):
_s = ("def %s(self, *args): return self._sock.%s(*args)\n\n"
"%s.__doc__ = _realsocket.%s.__doc__\n")
for _m in _socketmethods:
exec _s % (_m, _m, _m, _m)
exec(_s % (_m, _m, _m, _m))
del _m, _s
socket = SocketType = _socketobject

View file

@ -43,57 +43,56 @@ import_as_names = 285
dotted_as_names = 286
dotted_name = 287
global_stmt = 288
exec_stmt = 289
assert_stmt = 290
compound_stmt = 291
if_stmt = 292
while_stmt = 293
for_stmt = 294
try_stmt = 295
with_stmt = 296
with_var = 297
except_clause = 298
suite = 299
testlist_safe = 300
old_test = 301
old_lambdef = 302
test = 303
or_test = 304
and_test = 305
not_test = 306
comparison = 307
comp_op = 308
expr = 309
xor_expr = 310
and_expr = 311
shift_expr = 312
arith_expr = 313
term = 314
factor = 315
power = 316
atom = 317
listmaker = 318
testlist_gexp = 319
lambdef = 320
trailer = 321
subscriptlist = 322
subscript = 323
sliceop = 324
exprlist = 325
testlist = 326
dictmaker = 327
classdef = 328
arglist = 329
argument = 330
list_iter = 331
list_for = 332
list_if = 333
gen_iter = 334
gen_for = 335
gen_if = 336
testlist1 = 337
encoding_decl = 338
yield_expr = 339
assert_stmt = 289
compound_stmt = 290
if_stmt = 291
while_stmt = 292
for_stmt = 293
try_stmt = 294
with_stmt = 295
with_var = 296
except_clause = 297
suite = 298
testlist_safe = 299
old_test = 300
old_lambdef = 301
test = 302
or_test = 303
and_test = 304
not_test = 305
comparison = 306
comp_op = 307
expr = 308
xor_expr = 309
and_expr = 310
shift_expr = 311
arith_expr = 312
term = 313
factor = 314
power = 315
atom = 316
listmaker = 317
testlist_gexp = 318
lambdef = 319
trailer = 320
subscriptlist = 321
subscript = 322
sliceop = 323
exprlist = 324
testlist = 325
dictsetmaker = 326
classdef = 327
arglist = 328
argument = 329
list_iter = 330
list_for = 331
list_if = 332
gen_iter = 333
gen_for = 334
gen_if = 335
testlist1 = 336
encoding_decl = 337
yield_expr = 338
#--end constants--
sym_name = {}

View file

@ -16,4 +16,4 @@ import types
co = types.CodeType(0, 0, 0, 0, '\x04\x71\x00\x00', (),
(), (), '', '', 1, '')
exec co
exec(co)

View file

@ -1,5 +1,5 @@
test_cProfile
126 function calls (106 primitive calls) in 1.000 CPU seconds
127 function calls (107 primitive calls) in 1.000 CPU seconds
Ordered by: standard name
@ -14,6 +14,7 @@ test_cProfile
4 0.116 0.029 0.120 0.030 test_cProfile.py:78(helper1)
2 0.000 0.000 0.140 0.070 test_cProfile.py:89(helper2_indirect)
8 0.312 0.039 0.400 0.050 test_cProfile.py:93(helper2)
1 0.000 0.000 1.000 1.000 {exec}
12 0.000 0.000 0.012 0.001 {hasattr}
4 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
@ -44,6 +45,7 @@ test_cProfile.py:89(helper2_indirect) -> 2 0.006 0.040
2 0.078 0.100 test_cProfile.py:93(helper2)
test_cProfile.py:93(helper2) -> 8 0.064 0.080 test_cProfile.py:103(subhelper)
8 0.000 0.008 {hasattr}
{exec} -> 1 0.000 1.000 <string>:1(<module>)
{hasattr} -> 12 0.012 0.012 test_cProfile.py:115(__getattr__)
{method 'append' of 'list' objects} ->
{method 'disable' of '_lsprof.Profiler' objects} ->
@ -55,7 +57,7 @@ test_cProfile.py:93(helper2) -> 8 0.064 0.080
Function was called by...
ncalls tottime cumtime
<string>:1(<module>) <-
<string>:1(<module>) <- 1 0.000 1.000 {exec}
test_cProfile.py:103(subhelper) <- 8 0.064 0.080 test_cProfile.py:93(helper2)
test_cProfile.py:115(__getattr__) <- 16 0.016 0.016 test_cProfile.py:103(subhelper)
12 0.012 0.012 {hasattr}
@ -69,6 +71,7 @@ test_cProfile.py:78(helper1) <- 4 0.116 0.120
test_cProfile.py:89(helper2_indirect) <- 2 0.000 0.140 test_cProfile.py:60(helper)
test_cProfile.py:93(helper2) <- 6 0.234 0.300 test_cProfile.py:60(helper)
2 0.078 0.100 test_cProfile.py:89(helper2_indirect)
{exec} <-
{hasattr} <- 4 0.000 0.004 test_cProfile.py:78(helper1)
8 0.000 0.008 test_cProfile.py:93(helper2)
{method 'append' of 'list' objects} <- 4 0.000 0.000 test_cProfile.py:78(helper1)

View file

@ -39,7 +39,6 @@ raise_stmt
import_name
import_from
global_stmt
exec_stmt
assert_stmt
if_stmt
while_stmt

View file

@ -1,11 +1,12 @@
test_profile
127 function calls (107 primitive calls) in 1.000 CPU seconds
128 function calls (108 primitive calls) in 1.000 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
4 0.000 0.000 0.000 0.000 :0(append)
4 0.000 0.000 0.000 0.000 :0(exc_info)
1 0.000 0.000 1.000 1.000 :0(exec)
12 0.000 0.000 0.012 0.001 :0(hasattr)
8 0.000 0.000 0.000 0.000 :0(range)
1 0.000 0.000 0.000 0.000 :0(setprofile)
@ -28,13 +29,14 @@ test_profile
Function called...
:0(append) ->
:0(exc_info) ->
:0(exec) -> <string>:1(<module>)(1) 1.000
:0(hasattr) -> test_profile.py:115(__getattr__)(12) 0.028
:0(range) ->
:0(setprofile) ->
<string>:1(<module>) -> test_profile.py:30(testfunc)(1) 1.000
profile:0(profiler) -> profile:0(testfunc())(1) 1.000
profile:0(testfunc()) -> :0(setprofile)(1) 0.000
<string>:1(<module>)(1) 1.000
profile:0(testfunc()) -> :0(exec)(1) 1.000
:0(setprofile)(1) 0.000
test_profile.py:103(subhelper) -> :0(range)(8) 0.000
test_profile.py:115(__getattr__)(16) 0.028
test_profile.py:115(__getattr__) ->
@ -60,11 +62,12 @@ test_profile.py:93(helper2) -> :0(hasattr)(8) 0.012
Function was called by...
:0(append) <- test_profile.py:78(helper1)(4) 0.120
:0(exc_info) <- test_profile.py:78(helper1)(4) 0.120
:0(exec) <- profile:0(testfunc())(1) 1.000
:0(hasattr) <- test_profile.py:78(helper1)(4) 0.120
test_profile.py:93(helper2)(8) 0.400
:0(range) <- test_profile.py:103(subhelper)(8) 0.080
:0(setprofile) <- profile:0(testfunc())(1) 1.000
<string>:1(<module>) <- profile:0(testfunc())(1) 1.000
<string>:1(<module>) <- :0(exec)(1) 1.000
profile:0(profiler) <-
profile:0(testfunc()) <- profile:0(profiler)(1) 0.000
test_profile.py:103(subhelper) <- test_profile.py:93(helper2)(8) 0.400

View file

@ -15,7 +15,7 @@ class AllTest(unittest.TestCase):
def check_all(self, modname):
names = {}
try:
exec "import %s" % modname in names
exec("import %s" % modname, names)
except ImportError:
# Silent fail here seems the best route since some modules
# may not be available in all environments.
@ -23,7 +23,7 @@ class AllTest(unittest.TestCase):
verify(hasattr(sys.modules[modname], "__all__"),
"%s has no __all__ attribute" % modname)
names = {}
exec "from %s import *" % modname in names
exec("from %s import *" % modname, names)
if "__builtins__" in names:
del names["__builtins__"]
keys = set(names)

View file

@ -50,8 +50,6 @@ exec_tests = [
"import sys",
# ImportFrom
"from sys import v",
# Exec
"exec 'v'",
# Global
"global v",
# Expr
@ -169,7 +167,6 @@ exec_results = [
('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]),
('Module', [('Import', (1, 0), [('alias', 'sys', None)])]),
('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)]),
('Module', [('Exec', (1, 0), ('Str', (1, 5), 'v'), None, None)]),
('Module', [('Global', (1, 0), ['v'])]),
('Module', [('Expr', (1, 0), ('Num', (1, 0), 1))]),
('Module', [('Pass', (1, 0))]),

View file

@ -302,7 +302,7 @@ class RatTestCase(unittest.TestCase):
self.assertEqual(10.0, Rat(10))
def test_future_div(self):
exec future_test
exec(future_test)
# XXX Ran out of steam; TO DO: divmod, div, future division

View file

@ -395,6 +395,29 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises(IOError, execfile, os.curdir)
self.assertRaises(IOError, execfile, "I_dont_exist")
def test_exec(self):
g = {}
exec('z = 1', g)
if '__builtins__' in g:
del g['__builtins__']
self.assertEqual(g, {'z': 1})
exec(u'z = 1+1', g)
if '__builtins__' in g:
del g['__builtins__']
self.assertEqual(g, {'z': 2})
g = {}
l = {}
import warnings
warnings.filterwarnings("ignore", "global statement", module="<string>")
exec('global a; a = 1; b = 2', g, l)
if '__builtins__' in g:
del g['__builtins__']
if '__builtins__' in l:
del l['__builtins__']
self.assertEqual((g, l), ({'a': 1}, {'b': 2}))
def test_filter(self):
self.assertEqual(filter(lambda c: 'a' <= c <= 'z', 'Hello World'), 'elloorld')
self.assertEqual(filter(None, [1, 'hello', [], [3], '', None, 9, 0]), [1, 'hello', [3], 9])
@ -1172,7 +1195,7 @@ class BuiltinTest(unittest.TestCase):
"max(1, 2, key=1)", # keyfunc is not callable
):
try:
exec(stmt) in globals()
exec(stmt, globals())
except TypeError:
pass
else:
@ -1218,7 +1241,7 @@ class BuiltinTest(unittest.TestCase):
"min(1, 2, key=1)", # keyfunc is not callable
):
try:
exec(stmt) in globals()
exec(stmt, globals())
except TypeError:
pass
else:

View file

@ -136,7 +136,7 @@ def __%(method)s__(self, *args):
d = {}
for method in testmeths:
exec method_template % locals() in d
exec(method_template % locals(), d)
for k in d:
setattr(AllTests, k, d[k])
del d, k
@ -291,7 +291,7 @@ def check_exc(stmt, exception):
"""Raise TestFailed if executing 'stmt' does not raise 'exception'
"""
try:
exec stmt
exec(stmt)
except exception:
pass
else:

View file

@ -29,8 +29,8 @@ class CodeopTests(unittest.TestCase):
saved_stdout = sys.stdout
sys.stdout = cStringIO.StringIO()
try:
exec code in d
exec compile(str,"<input>","single") in r
exec(code, d)
exec(compile(str,"<input>","single"), r)
finally:
sys.stdout = saved_stdout
elif symbol == 'eval':

View file

@ -19,17 +19,17 @@ class TestSpecifics(unittest.TestCase):
self.assertRaises(SyntaxError, eval, 'lambda a,a=1:0')
self.assertRaises(SyntaxError, eval, 'lambda a=1,a=1:0')
try:
exec 'def f(a, a): pass'
exec('def f(a, a): pass')
self.fail("duplicate arguments")
except SyntaxError:
pass
try:
exec 'def f(a = 0, a = 1): pass'
exec('def f(a = 0, a = 1): pass')
self.fail("duplicate keyword arguments")
except SyntaxError:
pass
try:
exec 'def f(a): global a; a = 1'
exec('def f(a): global a; a = 1')
self.fail("variable is global and local")
except SyntaxError:
pass
@ -39,7 +39,7 @@ class TestSpecifics(unittest.TestCase):
def test_duplicate_global_local(self):
try:
exec 'def f(a): global a; a = 1'
exec('def f(a): global a; a = 1')
self.fail("variable is global and local")
except SyntaxError:
pass
@ -59,22 +59,22 @@ class TestSpecifics(unittest.TestCase):
m = M()
g = globals()
exec 'z = a' in g, m
exec('z = a', g, m)
self.assertEqual(m.results, ('z', 12))
try:
exec 'z = b' in g, m
exec('z = b', g, m)
except NameError:
pass
else:
self.fail('Did not detect a KeyError')
exec 'z = dir()' in g, m
exec('z = dir()', g, m)
self.assertEqual(m.results, ('z', list('xyz')))
exec 'z = globals()' in g, m
exec('z = globals()', g, m)
self.assertEqual(m.results, ('z', g))
exec 'z = locals()' in g, m
exec('z = locals()', g, m)
self.assertEqual(m.results, ('z', m))
try:
exec 'z = b' in m
exec('z = b', m)
except TypeError:
pass
else:
@ -85,7 +85,7 @@ class TestSpecifics(unittest.TestCase):
pass
m = A()
try:
exec 'z = a' in g, m
exec('z = a', g, m)
except TypeError:
pass
else:
@ -98,11 +98,12 @@ class TestSpecifics(unittest.TestCase):
return 12
return dict.__getitem__(self, key)
d = D()
exec 'z = a' in g, d
exec('z = a', g, d)
self.assertEqual(d['z'], 12)
def test_extended_arg(self):
longexpr = 'x = x or ' + '-x' * 2500
g = {}
code = '''
def f(x):
%s
@ -121,8 +122,8 @@ def f(x):
# EXTENDED_ARG/JUMP_ABSOLUTE here
return x
''' % ((longexpr,)*10)
exec code
self.assertEqual(f(5), 0)
exec(code, g)
self.assertEqual(g['f'](5), 0)
def test_complex_args(self):
@ -146,7 +147,7 @@ def f(x):
def test_argument_order(self):
try:
exec 'def f(a=1, (b, c)): pass'
exec('def f(a=1, (b, c)): pass')
self.fail("non-default args after default")
except SyntaxError:
pass

View file

@ -61,7 +61,7 @@ class CompilerTest(unittest.TestCase):
c = compiler.compile("try:\n 1/0\nexcept:\n e = 1\nfinally:\n f = 1",
"<string>", "exec")
dct = {}
exec c in dct
exec(c, dct)
self.assertEquals(dct.get('e'), 1)
self.assertEquals(dct.get('f'), 1)
@ -73,7 +73,7 @@ class CompilerTest(unittest.TestCase):
self.assert_('__doc__' in c.co_names)
c = compiler.compile('def f():\n "doc"', '<string>', 'exec')
g = {}
exec c in g
exec(c, g)
self.assertEquals(g['f'].__doc__, "doc")
def testLineNo(self):
@ -113,7 +113,7 @@ class CompilerTest(unittest.TestCase):
'<string>',
'exec')
dct = {}
exec c in dct
exec(c, dct)
self.assertEquals(dct.get('result'), 3)
def testGenExp(self):

View file

@ -55,7 +55,7 @@ def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
if verbose: print "checking", stmt
dict = {'a': deepcopy(a), 'b': b}
exec stmt in dict
exec(stmt, dict)
vereq(dict['a'], res)
t = type(a)
m = getattr(t, meth)
@ -73,7 +73,7 @@ def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
if verbose: print "checking", stmt
dict = {'a': deepcopy(a), 'b': b, 'c': c}
exec stmt in dict
exec(stmt, dict)
vereq(dict['a'], res)
t = type(a)
m = getattr(t, meth)
@ -91,7 +91,7 @@ def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
if verbose: print "checking", stmt
dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
exec stmt in dict
exec(stmt, dict)
vereq(dict['a'], res)
t = type(a)
while meth not in t.__dict__:
@ -3943,7 +3943,7 @@ def notimplemented():
def check(expr, x, y):
try:
exec expr in {'x': x, 'y': y, 'operator': operator}
exec(expr, {'x': x, 'y': y, 'operator': operator})
except TypeError:
pass
else:

View file

@ -67,7 +67,7 @@ statement or the built-in function eval():
>>> print sorted(a.keys())
[1, 2]
>>> exec "x = 3; print x" in a
>>> exec("x = 3; print x", a)
3
>>> print sorted(a.keys(), key=lambda x: (str(type(x)), x))
[1, 2, '__builtins__', 'x']

View file

@ -135,7 +135,7 @@ class DisTests(unittest.TestCase):
def func(count):
namespace = {}
func = "def foo():\n " + "".join(["\n "] * count + ["spam\n"])
exec func in namespace
exec(func, namespace)
return namespace['foo']
# Test all small ranges

View file

@ -2366,8 +2366,8 @@ def old_test4(): """
... '''>>> assert 1 < 2
... '''
... \"""
>>> exec test_data in m1.__dict__
>>> exec test_data in m2.__dict__
>>> exec(test_data, m1.__dict__)
>>> exec(test_data, m2.__dict__)
>>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
Tests that objects outside m1 are excluded:

View file

@ -87,7 +87,7 @@ class ExceptionTests(unittest.TestCase):
self.raise_catch(RuntimeError, "RuntimeError")
self.raise_catch(SyntaxError, "SyntaxError")
try: exec '/\n'
try: exec('/\n')
except SyntaxError: pass
self.raise_catch(IndentationError, "IndentationError")

View file

@ -278,7 +278,7 @@ def test_func_name():
cantset(f, "__name__", 1)
# test that you can access func.__name__ in restricted mode
s = """def f(): pass\nf.__name__"""
exec s in {'__builtins__':{}}
exec(s, {'__builtins__':{}})
def test_func_code():

View file

@ -153,7 +153,7 @@ def test_function():
# Tricky: f -> d -> f, code should call d.clear() after the exec to
# break the cycle.
d = {}
exec("def f(): pass\n") in d
exec("def f(): pass\n", d)
gc.collect()
del d
expect(gc.collect(), 2, "function")

View file

@ -10,7 +10,7 @@ def expectException(teststr, expected, failure=AssertionError):
"""Executes a statement passed in teststr, and raises an exception
(failure) if the expected exception is *not* raised."""
try:
exec teststr
exec(teststr)
except expected:
pass
else:

View file

@ -449,42 +449,6 @@ def f():
global a, b
global one, two, three, four, five, six, seven, eight, nine, ten
print 'exec_stmt' # 'exec' expr ['in' expr [',' expr]]
def f():
z = None
del z
exec 'z=1+1\n'
if z != 2: raise TestFailed, 'exec \'z=1+1\'\\n'
del z
exec 'z=1+1'
if z != 2: raise TestFailed, 'exec \'z=1+1\''
z = None
del z
import types
if hasattr(types, "UnicodeType"):
exec r"""if 1:
exec u'z=1+1\n'
if z != 2: raise TestFailed, 'exec u\'z=1+1\'\\n'
del z
exec u'z=1+1'
if z != 2: raise TestFailed, 'exec u\'z=1+1\''
"""
f()
g = {}
exec 'z = 1' in g
if '__builtins__' in g: del g['__builtins__']
if g != {'z': 1}: raise TestFailed, 'exec \'z = 1\' in g'
g = {}
l = {}
import warnings
warnings.filterwarnings("ignore", "global statement", module="<string>")
exec 'global a; a = 1; b = 2' in g, l
if '__builtins__' in g: del g['__builtins__']
if '__builtins__' in l: del l['__builtins__']
if (g, l) != ({'a':1}, {'b':2}): raise TestFailed, 'exec ... in g (%s), l (%s)' %(g,l)
print "assert_stmt" # assert_stmt: 'assert' test [',' test]
assert 1
assert 1, 1

View file

@ -107,7 +107,7 @@ def test_module_with_large_stack(module):
sys.path.append('')
# this used to crash
exec 'import ' + module
exec('import ' + module)
# cleanup
del sys.path[-1]

View file

@ -81,7 +81,7 @@ class TestImporter:
mod.__loader__ = self
if ispkg:
mod.__path__ = self._get__path__()
exec code in mod.__dict__
exec(code, mod.__dict__)
return mod

View file

@ -199,7 +199,7 @@ class TestRetrievingSourceCode(GetSourceBase):
m = sys.modules[name] = module(name)
m.__file__ = "<string>" # hopefully not a real filename...
m.__loader__ = "dummy" # pretend the filename is understood by a loader
exec "def x(): pass" in m.__dict__
exec("def x(): pass", m.__dict__)
self.assertEqual(inspect.getsourcefile(m.x.func_code), '<string>')
del sys.modules[name]
inspect.getmodule(compile('a=10','','single'))

View file

@ -49,7 +49,7 @@ class Test_MultibyteCodec(unittest.TestCase):
try:
for enc in ALL_CJKENCODINGS:
print >> open(TESTFN, 'w'), '# coding:', enc
exec open(TESTFN)
execfile(TESTFN)
finally:
os.unlink(TESTFN)

View file

@ -30,7 +30,7 @@ for stmt in ['d[x2] = 2',
'd.pop(x2)',
'd.update({x2: 2})']:
try:
exec stmt
exec(stmt)
except RuntimeError:
print "%s: caught the RuntimeError outside" % (stmt,)
else:

View file

@ -429,7 +429,7 @@ class CompileTestCase(unittest.TestCase):
st = parser.suite('x = 2; y = x + 3')
code = parser.compilest(st)
globs = {}
exec code in globs
exec(code, globs)
self.assertEquals(globs['y'], 5)
def test_compile_error(self):

View file

@ -205,15 +205,6 @@ def unoptimized_clash2():
return f
""")
# XXX could allow this for exec with const argument, but what's the point
check_syntax("""\
def error(y):
exec "a = 1"
def f(x):
return x + y
return f
""")
check_syntax("""\
def f(x):
def g():
@ -230,7 +221,7 @@ def f():
# and verify a few cases that should work
exec """
exec("""
def noproblem1():
from string import *
f = lambda x:x
@ -245,7 +236,7 @@ def noproblem3():
def f(x):
global y
y = x
"""
""")
print "12. lambdas"
@ -526,7 +517,7 @@ else:
print "eval() should have failed, because code contained free vars"
try:
exec g.func_code
exec(g.func_code)
except TypeError:
pass
else:

View file

@ -24,7 +24,7 @@ class Tests(unittest.TestCase):
# is correct
c = compile(s, '<string>', 'single')
vals = {}
exec c in vals
exec(c, vals)
assert vals['a'] == 1
assert vals['b'] == 2

View file

@ -44,22 +44,22 @@ hName = sys.argv[1]
# setup our creatorFunc to test the requested hash
#
if hName in ('_md5', '_sha'):
exec 'import '+hName
exec 'creatorFunc = '+hName+'.new'
exec('import '+hName)
exec('creatorFunc = '+hName+'.new')
print "testing speed of old", hName, "legacy interface"
elif hName == '_hashlib' and len(sys.argv) > 3:
import _hashlib
exec 'creatorFunc = _hashlib.%s' % sys.argv[2]
exec('creatorFunc = _hashlib.%s' % sys.argv[2])
print "testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2])
elif hName == '_hashlib' and len(sys.argv) == 3:
import _hashlib
exec 'creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2]
exec('creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2])
print "testing speed of _hashlib.new(%r)" % sys.argv[2]
elif hasattr(hashlib, hName) and callable(getattr(hashlib, hName)):
creatorFunc = getattr(hashlib, hName)
print "testing speed of hashlib."+hName, getattr(hashlib, hName)
else:
exec "creatorFunc = lambda x=hashlib.new : x(%r)" % hName
exec("creatorFunc = lambda x=hashlib.new : x(%r)" % hName)
print "testing speed of hashlib.new(%r)" % hName
try:

View file

@ -115,7 +115,7 @@ class Timer:
self.src = src # Save for traceback display
code = compile(src, dummy_src_name, "exec")
ns = {}
exec code in globals(), ns
exec(code, globals(), ns)
self.inner = ns["inner"]
def print_exc(self, file=None):

View file

@ -484,7 +484,7 @@ class Trace:
sys.settrace(self.globaltrace)
threading.settrace(self.globaltrace)
try:
exec cmd in dict, dict
exec(cmd, dict, dict)
finally:
if not self.donothing:
sys.settrace(None)
@ -497,7 +497,7 @@ class Trace:
sys.settrace(self.globaltrace)
threading.settrace(self.globaltrace)
try:
exec cmd in globals, locals
exec(cmd, globals, locals)
finally:
if not self.donothing:
sys.settrace(None)