当前位置: 首页 > news >正文

exec()在不同namespace执行结果的区别

记录一个很tricky的问题,下面这段code在执行'func1'时会出现NameError: name 'List' is not defined,但执行'func2'时一切正常。

import typescontent = """
from typing import Listclass GeneratedData:qna: List"""def func1(content):exec(content)_locals = {k: v for k, v in locals().items()}print(len(_locals))def func2(content):m = types.ModuleType("promptflow.dummy")exec(content, m.__dict__)_locals = m.__dict__print(len(_locals))

原因是exec(content)执行的时候import statement都直接修改了locals, 导致后面的code执行的时候在globals里找不到import的东西,但是如果给一个module的话相当于在一个独立的namespace里运行,就不会出现找不到的问题。附上问copilot chat得到的回复:

The difference between the two functions is that func2 creates a new module using types.ModuleType and executes the code within that module's namespace, while func1 executes the code in the current namespace.

When you execute code in the current namespace, any imports or definitions made in that code will affect the current namespace. So if the code being executed contains an import statement that is not defined in the current namespace, you will get an error.

On the other hand, when you execute code in a new module's namespace, any imports or definitions made in that code will only affect that module's namespace. So if the code being executed contains an import statement that is not defined in the current namespace, it will not raise an error as long as the import is defined in the imported module.

In summary, func2 works because it creates a new module and executes the code within that module's namespace, while func1 executes the code in the current namespace, which can cause import errors.

http://www.lryc.cn/news/89781.html

相关文章:

  • 人工智能革命中的22个隐藏职业:推动科技行业的变革
  • 算法题3 — 求字符串中的最长子串
  • 【FreeRTOS】——中断优先级设置中断相关寄存器临界段代码保护调度器挂起与恢复
  • 1.2 什么是eBPF?(下)
  • 掌握哪些测试技术才能说自己已经学成了?
  • 什么是C语言?
  • SAP-物料主数据-质量管理视图字段解析
  • TOP RPA·脱普×实在丨日用品企业脱普签约实在智能,构建全域数据智能运营系统
  • 【Android】Handler(四)Looper的相关知识点
  • Redis缓存雪崩及解决办法
  • Maven私服仓库配置-Nexus详解
  • Systrace系列10 —— Binder 和锁竞争解读
  • React Hooks中使用useState异步回调获取不到最新值的问题
  • JavaScript 高级 (完结)
  • 【P30】JMeter 事务控制器(Transaction Controller)
  • 【MySQL】MySQL的事务原理和实现?
  • S7-300Smart1200的ISO on TCP通信
  • Spark写入Hive报错Mkdir failed on :com.alibaba.jfs.JindoRequestPath
  • 分布式id解决方法--雪花算法
  • 5年经验之谈:月薪3000到30000,测试工程师的变“行”记
  • PMP考试都是什么题?
  • macbook2023系统清理软件cleanmymac中文版
  • 基于Python+AIML+Tornado的智能聊天机器人(NLP+深度学习)含全部工程源码+语料库 适合个人二次开发
  • 算法Day15 | 层序遍历,102,107,199,637,429,515,116,117,104,111,226,101
  • Prometheus+Grafana学习(十一)安装使用pushgateway
  • 深入理解C/C++预处理器指令#pragma once以及与ifndef的比较
  • git 环境配置 + gitee拉取代码
  • 港联证券|港股拥抱特专科技企业 内资券商“修炼内功”蓄势而为
  • 多项创新技术加持,实现零COGS的Microsoft Editor语法检查器
  • Python编程环境搭建:Windows中如何安装Python