1

My module path = "..\blah\blah\myfolder\mymodule.py" contains:

print('hi')

Code execution:

exec(compile(open(path, 'rb').read(), path, 'exec'))

and

exec(open(path, 'rb').read())

give the same result.

Why is compile() needed?

ugorek
  • 113
  • 4
  • Obligatory [eval is evil](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) plug – matszwecja Aug 14 '23 at 09:17

1 Answers1

1

They are identical in your case, i.e. exec and eval use compile if get the string as an input. But compile can be used to precompile the code that will be repeatedly executed with exec (or eval), making it run faster because you don't need to compile the code each time. Consider:

compiled_code = compile(open(path, 'rb').read(), path, 'exec')
for _ in range(10**9):
    exec(compiled_code)
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48