動態創建模塊級功能對象例如,我可以從字符串
我想創建一個函數對象。
mystr = \
"""
def foo(a=1):
print a
pass
"""
但是,使用編譯(myStr中)將只給我一個代碼對象。我想擁有模塊級別的函數對象,就像字符串是源代碼的一部分。
這可以實現嗎?
動態創建模塊級功能對象例如,我可以從字符串
我想創建一個函數對象。
mystr = \
"""
def foo(a=1):
print a
pass
"""
但是,使用編譯(myStr中)將只給我一個代碼對象。我想擁有模塊級別的函數對象,就像字符串是源代碼的一部分。
這可以實現嗎?
exec mystr
將執行你給的代碼。
是使用exec
:
>>> mystr = \
"""
def foo(a=1):
print a
pass
"""
>>> exec mystr
>>> foo
<function foo at 0x0274F0F0>
您還可以使用compile
在這裏,它支持像exec
,eval
,single
模式:
In [1]: mystr = \
"""
def foo(a=1):
print a
pass
"""
...:
In [2]: c=compile(mystr,"",'single')
In [3]: exec c
In [4]: foo
Out[4]: <function __main__.foo>
幫助上compile
:
In [5]: compile?
Type: builtin_function_or_method
String Form:<built-in function compile>
Namespace: Python builtin
Docstring:
compile(source, filename, mode[, flags[, dont_inherit]]) -> code object
Compile the source string (a Python module, statement or expression)
into a code object that can be executed by the exec statement or eval().
The filename will be used for run-time error messages.
The mode must be 'exec' to compile a module, 'single' to compile a
single (interactive) statement, or 'eval' to compile an expression.
The flags argument, if present, controls which future statements influence
the compilation of the code.
The dont_inherit argument, if non-zero, stops the compilation inheriting
the effects of any future statements in effect in the code calling
compile; if absent or zero these statements do influence the compilation,
in addition to any features explicitly specified.
什麼的優點如果'exec'獨自完成這項工作,使用'compile'和'exec'? – fiatjaf 2013-09-20 20:14:49