735Tesla
735Tesla

Reputation: 3241

Where is python exec?

I know it is possible to get access to builtin functions with something like:

object().__reduce__()[0].__globals__["__builtins__"]

And this seems to work for most functions. However, I cannot seem to be able to find exec(). I am pretty certain it is a builtin function, so why wouldn't it appear in __builtins__? Both eval() and execfile() are there.

I am using python 2.7

[EDIT]

A much simpler way to get to globals is with the builtin function globals() :) So the above can be reduced to: globals()['__builtins__'].__dict__

Upvotes: 1

Views: 491

Answers (2)

nneonneo
nneonneo

Reputation: 179452

exec is a keyword, like print. Therefore it is not a function.

You can see this if you attempt to assign to it:

>>> print = 3
  File "<stdin>", line 1
    print = 3
          ^
SyntaxError: invalid syntax
>>> exec = 3
  File "<stdin>", line 1
    exec = 3
         ^
SyntaxError: invalid syntax
>>> eval = 3
>>> 

If you're hellbent on calling exec without using the word exec, you can do something like this:

import ctypes

ctypes.pythonapi.PyRun_SimpleString("print 'hello world'")

which abuses the CPython API to execute a piece of code (which can be arbitrarily long).

And if you need control over the globals and locals, use PyRun_String:

Py_file_input = 257 # Include/Python.h
def my_exec(s, _globals, _locals):
    return ctypes.pythonapi.PyRun_String(s, Py_file_input, ctypes.py_object(_globals), ctypes.py_object(_locals))

my_exec("print 3 + 3", globals(), locals())

Upvotes: 2

user2555451
user2555451

Reputation:

In Python 2.x, exec is a statement, not a function:

>>> # Python 2.x interpreter
>>> 'exec' in dir(__builtins__)
False
>>> callable(exec)  # This would return True if exec was a function
  File "<stdin>", line 1
    callable(exec)
                ^
SyntaxError: invalid syntax
>>>

In Python 3.x however, exec was converted into a function:

>>> # Python 3.x interpreter
>>> 'exec' in dir(__builtins__)
True
>>> callable(exec)
True
>>>

Upvotes: 3

Related Questions