0

I'm new to python and now making some program with it.

I have two files, which are trans.py and main.py.

In trans.py,

from math import *
from numpy import *


def matrix_T(d): 
    global mat_A, mat_B, mat_C, mat_D   
    temp_A, temp_B, temp_C, temp_D = mat_A, mat_B, mat_C, mat_D
    mat_A = 1.0*temp_A + d*temp_C     
    mat_B = 1.0*temp_B + d*temp_D
    mat_C = 1.0*temp_C
    mat_D = 1.0*temp_D

In main.py,

from trans import *

global mat_A, mat_B, mat_C, mat_D
mat_A = 1.0
mat_B = 0.0
mat_C = 0.0
mat_D = 1.0

print(mat_A, mat_B, mat_C, mat_D)

matrix_T(0.0)

print(mat_A, mat_B, mat_C, mat_D)

and when I run main.py, of course get this error.

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    matrix_T(0.0)
  File "trans.py", line 6, in matrix_T
    temp_A, temp_B, temp_C, temp_D = mat_A. mat_B, mat_C, mat_D
NameError: global name 'mat_A' is not defined

Since I thought I defined global variable mat_A to mat_D, how could I avoid this problem?

Thanks in advance.

SangMin Ahn
  • 5
  • 1
  • 1
  • 3
  • 13
    `global` does not mean "cross module". You should avoid `global` as much as possible. Pass values into functions using parameters and `return` values from them. Don't get used to using a "global" scope. – deceze Oct 25 '16 at 12:15
  • Duplicate of http://stackoverflow.com/a/13034908/4080476 – Brian Pendleton Oct 25 '16 at 12:20
  • 1
    Friends don't let friends use globals. – PM 2Ring Oct 25 '16 at 12:32
  • @L3viathan Brian has already linked that question, but I'm not happy to use that as a dupe target because the accepted answer encourages the (unnecessary) use of globals. – PM 2Ring Oct 25 '16 at 12:43

1 Answers1

6

First point: global <name> doesn't define a variable, it only tells the runtime that in this function, "<name>" will have to be looked up in the "global" namespace instead of the local one.

Second point : in Python, the "global" namespace really means the current module's top-level namespace. And that's the most "global" namespace you'll get in Python (hopefully). So defining variables by the same name in another module won't make them available to your function (and that's a GoodThing).

Last point: don't use globals anyway. Pass needed arguments to your functions, and make your functions return computed values. globals are evil.

deceze
  • 510,633
  • 85
  • 743
  • 889
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118