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

Python动态导入模块变量时报'module' is not iterable错误如何解决

错误原因

  • 错误使用导入语法:__import__('my_file')返回的是my_file模块对象本身,不是模块内的变量。你写的'my_file'.format(allowlist)没有任何作用,因为my_file字符串中没有需要替换的占位符,最终allowlist变量被赋值为模块对象,对模块对象执行in判断自然会抛出'module' is not iterable的类型错误。
  • 没有正确从模块中提取动态变量名对应的属性:你拼接得到的var1是字符串类型的变量名,需要通过属性获取方法从模块中取出对应的列表值。

解决方案

修正后的代码如下:

usri = input('what is your favorite pastry')
# compare_count是值为1的计数器,用于拼接变量名
compare_count = 1
# 拼接得到目标变量名的字符串形式
target_var_name = f'var{compare_count}'
# 导入my_file模块
import my_file
# 从模块中取出对应变量的值,第三个参数为变量不存在时的默认值,可避免报错
allowlist = getattr(my_file, target_var_name, [])

# 检查用户输入是否属于导入的列表成员
if usri in allowlist:
    print('user input was found')
else:
    print('user input wasn\'t found')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:06:02