2014-10-25 17:07:09 -04:00
|
|
|
# test compile builtin
|
|
|
|
|
2020-08-20 20:30:09 -04:00
|
|
|
try:
|
|
|
|
compile
|
|
|
|
except NameError:
|
|
|
|
print("SKIP")
|
|
|
|
raise SystemExit
|
2014-10-26 11:38:28 -04:00
|
|
|
|
|
|
|
def test():
|
2015-04-04 17:05:30 -04:00
|
|
|
global x
|
|
|
|
|
2014-10-26 11:38:28 -04:00
|
|
|
c = compile("print(x)", "file", "exec")
|
|
|
|
|
|
|
|
try:
|
|
|
|
exec(c)
|
|
|
|
except NameError:
|
|
|
|
print("NameError")
|
2014-10-25 17:07:09 -04:00
|
|
|
|
2015-04-04 17:05:30 -04:00
|
|
|
# global variable for compiled code to access
|
|
|
|
x = 1
|
|
|
|
|
2014-10-25 17:07:09 -04:00
|
|
|
exec(c)
|
|
|
|
|
2014-10-26 11:38:28 -04:00
|
|
|
exec(c, {"x":2})
|
|
|
|
exec(c, {}, {"x":3})
|
2014-10-25 17:07:09 -04:00
|
|
|
|
2015-04-04 17:05:30 -04:00
|
|
|
# single/eval mode
|
2020-08-20 20:30:09 -04:00
|
|
|
exec(compile("if 1: 10 + 1\n", "file", "single"))
|
|
|
|
exec(compile("print(10 + 2)", "file", "single"))
|
|
|
|
print(eval(compile("10 + 3", "file", "eval")))
|
2015-04-04 17:05:30 -04:00
|
|
|
|
|
|
|
# bad mode
|
|
|
|
try:
|
|
|
|
compile('1', 'file', '')
|
|
|
|
except ValueError:
|
|
|
|
print("ValueError")
|
|
|
|
|
|
|
|
# exception within compiled code
|
|
|
|
try:
|
|
|
|
exec(compile('noexist', 'file', 'exec'))
|
|
|
|
except NameError:
|
|
|
|
print("NameError")
|
|
|
|
print(x) # check 'x' still exists as a global
|
|
|
|
|
2023-05-18 22:15:55 -04:00
|
|
|
# hashing a compiled function object
|
|
|
|
print(type(hash(compile("", "", "exec"))))
|
|
|
|
|
2020-08-20 20:30:09 -04:00
|
|
|
test()
|