You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不调用原函数的情况下利用装饰器元数据执行Python函数?是否可行?

如何在不调用原函数的情况下利用装饰器元数据执行Python函数?是否可行?

当然可行!不过你当前的实现有个关键问题——只有当你实际调用被装饰的函数时,元数据才会被存入memory_storage。如果想实现「不调用原函数就能收集元数据并执行函数」的效果,我们只需要调整装饰器的逻辑,让元数据在装饰函数的阶段就被存储,而不是等到函数执行时。

先分析下你现有代码的问题:
你的装饰器把元数据添加逻辑放在了wrapper函数内部,而wrapper只有在调用被装饰函数(比如print_weep())的时候才会触发。这就导致如果不手动调用这些函数,memory_storage会是空的,自然没法通过元数据执行它们。

修改后的实现代码

import functools

memory_storage = []

def memory(func_names, description):
    def decorator(func):
        # 核心改动:把元数据存储移到这里!装饰函数时就存入,无需等待函数执行
        memory_storage.append({
            "func_names": func_names,
            "description": description,
            "function": func
        })
        
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # 保留原函数的执行逻辑(如果业务需要调用原函数的话)
            return func(*args, **kwargs)
        return wrapper
    return decorator

@memory(
    func_names=['print_weep'],
    description="This method will print the weep"
)
def print_weep():
    print("weep")

@memory(
    func_names=['print_hello'],
    description="This method will print hello"
)
def print_hello():
    print("hello")

def execute_functions():
    for entry in memory_storage:
        print(f"Executing function {entry['func_names'][0]}: {entry['description']}")
        entry['function']()  # 直接调用存储的函数对象

print("Stored Metadata:", memory_storage)
execute_functions()

改动说明

  • 核心调整是把元数据的append操作从wrapper移到了decorator函数里。这样当Python加载脚本、装饰器自动应用到目标函数上时,元数据就被存入memory_storage了,完全不需要手动调用print_weep()或print_hello()。
  • wrapper函数现在只负责保留原函数的调用能力,如果你的业务场景不需要直接调用原函数,甚至可以简化掉wrapper,直接返回原函数即可。

运行这段代码你会发现:

  1. 无需手动触发原函数,memory_storage已经包含了所有函数的元数据
  2. execute_functions()可以顺利遍历元数据并执行对应的函数

备注:内容来源于stack exchange,提问作者chinna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 08:28:03