0

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

Community
  • 1
  • 1
NoobTom
  • 555
  • 1
  • 9
  • 21

1 Answers1

3

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.

aychedee
  • 24,871
  • 8
  • 79
  • 83
  • Thank you! i feel so dumb now. I though i could import only functions and files with that import command. – NoobTom Feb 26 '13 at 08:58
  • Every language has it's own concept of the global namespace, so don't worry. Python has a per module namespace. And each function inside a module is inside it's own closure. You generally don't need to use the `global` keyword – aychedee Feb 26 '13 at 18:39