SangMin Ahn SangMin Ahn - 11 months ago 88
Python Question

NameError: global name 'name' is not defined (while it is defined.)

I'm new to python and now making some program with it.
I have two files, which are

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


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)


print(mat_A, mat_B, mat_C, mat_D)

and when I run
, of course get this error.

Traceback (most recent call last):
File "", line 11, in <module>
File "", 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.

Answer Source

First point: global <name> doesn't define a variable, it only tells the runtime that in this function, "" 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.