SangMin Ahn SangMin Ahn - 1 month ago 7
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

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.

Answer

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.

Comments