在模块级别使用Pandas全局变量时出现未定义错误的问题排查
问题原因与解决方案
你在helperFunction里用global my_df声明的全局变量,只属于helperFunction这个模块,并非main模块的全局变量。所以main.py里直接访问my_df会提示未定义——因为main的命名空间里根本没有这个变量,而helperFunction的命名空间里才有。
以下是几种可行的解决方式:
方案1:从helperFunction模块直接引用变量
修改main.py的print语句,明确指定从helperFunction模块获取变量:
import helperFunction def main(): helperFunction.createGlobalVars('the_file.csv') print(helperFunction.my_df.head()) # 添加模块前缀访问 if __name__=='__main__': main()
方案2:让函数返回DataFrame(推荐)
全局变量容易造成代码耦合,更规范的做法是让函数返回创建好的DataFrame,在main里接收使用:
修改helperFunction.py:
import pandas as pd def createGlobalVars(file_path): my_df = pd.read_csv(file_path) print(my_df.head()) return my_df # 返回创建好的DataFrame
修改main.py:
import helperFunction def main(): my_df = helperFunction.createGlobalVars('the_file.csv') # 接收返回值 print(my_df.head()) if __name__=='__main__': main()
方案3:在helperFunction模块定义模块级变量
如果确实需要跨模块共享变量,可以在helperFunction模块顶层先定义变量,再在函数里修改:
helperFunction.py:
import pandas as pd my_df = None # 定义模块级变量 def createGlobalVars(file_path): global my_df # 声明要修改的是模块级的my_df my_df = pd.read_csv(file_path) print(my_df.head())
main.py里同样需要通过helperFunction.my_df来访问这个变量。
内容的提问来源于stack exchange,提问作者inzikind
相关产品推荐
相关产品推荐

