Home > Dive Into Python > The Power Of Introspection > Executing code dynamically | << >> |
diveintopython.org | |
Python for experienced programmers | |
Python has the ability to execute arbitrary strings as Python code. This means that you can build code dynamically as strings and then execute it, just as if you had typed it in before running the program.
Many other scripting languages can do this, including Perl, JavaScript, and Transact/SQL in SQL Server. But there are differences in Python's implementation, especially compared to Transact/SQL, so watch closely.
if type(object) == ModuleType: name = object.__name__ exec("import %s" % name)
The exec function, in its simplest form, takes a string and executes it as Python code in the current content. That means that this code will import the module called name and make available all its attributes and methods, just as if you had coded an import statement with the name directly. But of course you couldn't have done that, because you didn't know the name before you ran the program.
Example 2.12. Accessing variables within exec
>>> x = 1 >>> exec("print x")1 >>> exec("x = 2")
>>> print x
2
A complementary function to exec is eval. While exec executes a command, eval evaluates an expression and returns its value. Of course, some expressions (like list.pop()) have side effects, but generally you will use eval strictly for the expression's return value.
Example 2.13. Introducing eval
>>> x = 1 >>> y = 2 >>> s = "x" >>> eval(s)1 >>> s = "y*2" >>> eval(s)
4 >>> s = "s" >>> eval(s)
's'
Example 2.14. Using eval in apihelper.py
>>> import odbchelper >>> name = "odbchelper" >>> e = "buildConnectionString" >>> "%s.%s" % (name, e)'odbchelper.buildConnectionString' >>> eval("%s.%s" % (name, e))
![]()
>>> func = eval("%s.%s" % (name, e)) >>> func({"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}) 'server=mpilgrim;uid=sa;database=master;pwd=secret'
![]() | This is not new; this is just basic string formatting. |
![]() | This is equivalent to eval("odbchelper.buildConnectionString"), which evaluates to an object, the function buildConnectionString in the module odbchelper. Did I mention that everything in Python is an object? |
![]() | You can assign the return value of eval to a variable or do whatever else you want with it. In this case, you can use it to call the buildConnectionString function just as if you were calling it directly. You can also access the function's attributes, like its doc string, as we'll see shortly. |
« type, str, dir, other built-in functions | Filtering lists » |