Python 我可以从字符串动态创建模块级函数对象吗

Python 我可以从字符串动态创建模块级函数对象吗,python,Python,比如说, 我想从中创建一个函数对象 mystr = \ """ def foo(a=1): print a pass """ 然而,使用compile(mystr)只会给我一个code对象。我想要模块级的函数对象,就像字符串是源代码的一部分一样 这能实现吗?exec mystr 将执行您给定的代码。exec mystr 将执行您给定的代码。是使用: >>mystr=\ """ def foo(a=1): 打印 通过 """ >>>执行官 >>>福 是使用: >>mystr=\

比如说,

我想从中创建一个函数对象

mystr = \
"""
def foo(a=1): 
    print a
    pass
"""
然而,使用compile(mystr)只会给我一个code对象。我想要模块级的函数对象,就像字符串是源代码的一部分一样


这能实现吗?

exec mystr


将执行您给定的代码。

exec mystr

将执行您给定的代码。

是使用:

>>mystr=\
"""
def foo(a=1):
打印
通过
"""
>>>执行官
>>>福
是使用:

>>mystr=\
"""
def foo(a=1):
打印
通过
"""
>>>执行官
>>>福

您也可以在此处使用
编译
,它支持
执行
评估
单一
等模式:

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>
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.

您也可以在此处使用
编译
,它支持
执行
评估
单一
等模式:

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>
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
有什么好处?如果单独使用
exec
执行任务,使用
compile
然后使用
exec
有什么好处?