I'm trying to strengthen my Python skills, and I came across Open-Source code for Saltstack that is using types.FunctionType, and I don't understand what's going on.
salt.cloud.clouds.cloudstack.py
Function create()
has the following bit of code:
kwargs = {
'name': vm_['name'],
'image': get_image(conn, vm_),
'size': get_size(conn, vm_),
'location': get_location(conn, vm_),
}
The function get_image, and get_size are passed to a function 'namespaced_function' as so:
get_size = namespaced_function(get_size, globals())
get_image = namespaced_function(get_image, globals())
salt.utils.functools.py
Has the namespaced function
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
I can see that they are dynamically creating a function get_image
, but I don't understand the benefit of doing it this way. Why not just create the function?