python动态创建函数_Python的types.FunctionType如何创建动态函数?

在提升Python技能时,遇到Saltstack源码中关于动态创建函数的疑惑。在`salt.cloud.clouds.cloudstack.py`的`create()`函数内,`get_image`和`get_size`通过`namespaced_function`进行了命名空间功能的重定义。`salt.utils.functools.py`中的`namespaced_function`函数用于根据新的全局字典(global_dict)克隆并重新定义函数,保持或更新原始命名空间的上下文。这种做法的优点在于动态调整函数的作用域,但为何不直接创建函数仍待理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我正在努力增强我的

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,但我不明白这样做的好处.为什么不创建这个功能呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值