Python global dict across different file script

2019-08-29 07:47发布

问题:

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.