将`from constants import API_TOKEN`改为`import constants`为何引发错误?
问题原因
直接import constants后,代码里仍用API_TOKEN直接引用时,Python和PyCharm无法将其关联到constants模块中的常量;同时因为代码里没通过模块名访问内容,PyCharm判定导入的模块未被使用,所以抛出两个提示。
解决步骤
- 修改常量引用方式:把所有
API_TOKEN改为constants.API_TOKEN,示例:# 原错误写法 print(API_TOKEN) # 修改后 print(constants.API_TOKEN) - 可选简化写法:给模块起别名,先修改导入语句:
再用别名引用常量:import constants as constprint(const.API_TOKEN) - 备选方案(若需导入多个常量):一次性导入需要的所有常量:
from constants import API_TOKEN, NEW_CONSTANT_A, NEW_CONSTANT_B
内容的提问来源于stack exchange,提问作者brec
相关产品推荐
相关产品推荐

