You need to enable JavaScript to run this app. Python两文件存在同名return_list函数,除合并外还有什么单执行方案
优惠活动
大模型
产品
解决方案
定价
更多

Python两文件存在同名return_list函数,除合并外还有什么单执行方案

现有代码问题修正

你给出的代码存在两处基础语法/逻辑错误,需先修正才能正常运行:

  • 2.py中for i lin list_是拼写错误,应为for i in list_;且return写在循环内部会导致第一次迭代就返回,list.append()返回None,无法得到id列表。
  • 1.py中导入语法错误,不能导入自身import 1.py,应为导入2模块,且不需要加.py后缀。

无需合并文件的解决方案

以下方案均可实现两个return_list函数各自仅执行一次操作,不需要合并文件:

1. 函数属性标记法(推荐,无额外依赖)

给每个return_list函数添加专属的执行标记属性,首次调用完成后标记为已执行,后续调用直接返回首次执行的结果,不会重复跑逻辑:

# 2.py 示例代码
list_ = [{'id': '1', 'name': 'ABC', 'email': 'abc@gmail.com', 'role': 'Tester'},
         {'id': '2', 'name': 'CDE', 'email': 'cde@gmail.com', 'role': 'Developer'}]

def return_list():
    # 已执行标记判断
    if hasattr(return_list, '_executed'):
        return return_list._result
    l = []
    for i in list_:
        l.append(i['id'])
    # 这里放你第一部分的操作逻辑(爬取等)
    # 标记已执行,缓存结果
    return_list._executed = True
    return_list._result = l
    return l
# 1.py 示例代码
import 2 as module2

# 1.py自身的return_list函数
def return_list():
    if hasattr(return_list, '_executed'):
        return return_list._result
    # 调用2.py的return_list(2的函数只会执行一次)
    ids_from_module2 = module2.return_list()
    # 这里放你第二部分的操作逻辑
    return_list._executed = True
    return_list._result = ids_from_module2
    return ids_from_module2

def test():
    list_ids = return_list()
    return list_ids

2. 模块级缓存法

Python的模块导入仅会执行一次,你可以把函数执行结果存在模块的全局变量里,后续调用直接读取变量即可:

# 2.py 模块缓存示例
_list_cache = None
def return_list():
    global _list_cache
    if _list_cache is not None:
        return _list_cache
    # 你的执行逻辑
    l = [i['id'] for i in list_]
    _list_cache = l
    return l

3. 标准库缓存装饰器

如果你的函数没有可变入参,可以用functools.lru_cache装饰器实现一次执行多次返回:

from functools import lru_cache

@lru_cache(maxsize=None)
def return_list():
    # 你的执行逻辑
    return [i['id'] for i in list_]

内容的提问来源于stack exchange,提问作者sim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 03:21:03