我正在努力增强我的
Python技能,我遇到了使用types.FunctionType的
Open-Source code for Saltstack,我不明白发生了什么.
salt.cloud.clouds.cloudstack.py
函数create()包含以下代码:
kwargs = {
'name': vm_['name'],
'image': get_image(conn, vm_),
'size': get_size(conn, vm_),
'location': get_location(conn, vm_),
}
函数get_image和get_size传递给函数’namespaced_function’,如下所示:
get_size = namespaced_function(get_size, globals())
get_image = namespaced_function(get_image, globals())
salt.utils.functools.py
具有命名空间功能
def namespaced_function(function, global_dict, defaults=None, preserve_context=False):
'''
Redefine (clone) a function under a different globals() namespace scope
preserve_context:
Allow keeping the context taken from orignal namespace,
and extend it with globals() taken from
new targetted namespace.
'''
if defaults is None:
defaults = function.__defaults__
if preserve_context:
_global_dict = function.__globals__.copy()
_global_dict.update(global_dict)
global_dict = _global_dict
new_namespaced_function = types.FunctionType(
function.__code__,
global_dict,
name=function.__name__,
argdefs=defaults,
closure=function.__closure__
)
new_namespaced_function.__dict__.update(function.__dict__)
return new_namespaced_function
我可以看到他们正在动态创建一个函数get_image,但我不明白这样做的好处.为什么不创建这个功能呢?