Python global dict across different file script

萝らか妹 提交于 2019-12-11 20:32:55

问题


Hello. I am trying to use a global dict created in main.py, which is called in functions.py. In my main.py I have:

import sys,os,...
import functions.py #import my second file

matrix = {}
matrix_do_something
search_the_matrix(value) #which is defined in functions.py

#FILE: functions.py
def search_the_matrix(value):
    global matrix
    if value in matrix:
        return True
    else:
        return False

and I get this error:

NameError: global name 'matrix' is not defined

I have read a solution on stackoverflow, which says to put everything in a global file and then call from every file global.matrix[value] but I don't want this. I want just call it matrix and think of it as my global matrix. Is this possible? Thank you in advance


回答1:


In functions.py you would have to import it

from main import matrix

Though I would want to come up with a better name for my module than main.

If you want an object to be available in a module / file you need to either create it there or import it from somewhere else.



来源:https://stackoverflow.com/questions/15084615/python-global-dict-across-different-file-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!